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]

851 KB
Raw Blame
import asyncio
from collections.abc import Mapping
from contextlib import ExitStack
from typing import Final
from types import SimpleNamespace
import json
from datetime import datetime, timedelta, timezone
from uuid import UUID

import litellm
import pytest
import yaml
from fastapi.testclient import TestClient

from unittest.mock import AsyncMock, MagicMock, patch

from fastapi import HTTPException
from pydantic import JsonValue

import inspect

from litellm.models.project import LiteLLM_ProjectTable
from litellm.proxy._types import (
    GenerateKeyResponse,
    GenerateKeyRequest,
    KeyManagementRoutes,
    NewUserRequest,
    LiteLLM_BudgetTable,
    LiteLLM_ObjectPermissionBase,
    LiteLLM_OrganizationTable,
    LiteLLM_ProjectTableCachedObj,
    LiteLLM_TeamTable,
    LiteLLM_TeamTableCachedObj,
    LiteLLM_UserTable,
    LiteLLM_VerificationToken,
    LiteLLMKeyType,
    LitellmUserRoles,
    Member,
    ProxyException,
    RegenerateKeyRequest,
    ResetSpendRequest,
    UpdateKeyRequest,
)
from litellm.models.object_permission import LiteLLM_ObjectPermissionTable
from litellm.proxy.auth.auth_checks import (
    delete_cache_key_object,
    jwt_key_mapping_cache_key,
)
from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache, project_cache_key
from litellm.constants import PROXY_DB_LOOKUP_STALL_WINDOW_SECONDS
from litellm.proxy.db.db_lookup_gate import db_lookup_stall_tracker
from litellm.litellm_core_utils.duration_parser import duration_in_seconds
from litellm.proxy.management_endpoints.key_management_endpoints import (
    _check_key_project_team,
    _check_key_project_team_on_mutation,
    _check_org_key_limits,
    _check_project_key_limits,
    _check_team_key_limits,
    _is_team_key,
    _key_generation_required_param_check,
    _personal_key_generation_check,
    _team_key_generation_check,
    _common_key_generation_helper,
    _member_key_request,
    _team_admin_requests_member_key,
    KeyProjectBindingError,
    _effective_key_after_update,
    _effective_key_for_generate,
    _enforce_custom_key_policy,
    _enforce_upperbound_key_params,
    _execute_virtual_key_regeneration,
    _get_and_validate_existing_key,
    list_key_helper,
    persist_deleted_verification_tokens,
    _process_single_key_update,
    _requested_end_user_budget_id,
    _save_deleted_verification_token_records,
    _transform_verification_tokens_to_deleted_records,
    _validate_end_user_budget_id_change,
    _validate_max_budget,
    _validate_reset_spend_value,
    _validate_update_key_data,
    can_modify_verification_token,
    check_org_key_model_specific_limits,
    check_team_key_model_specific_limits,
    delete_verification_tokens,
    generate_key_fn,
    generate_key_helper_fn,
    generate_service_account_key_fn,
    key_aliases,
    key_generation_check,
    list_keys,
    prepare_key_update_data,
    prepare_metadata_fields,
    reset_key_spend_fn,
    update_key_fn,
    validate_key_list_check,
    validate_key_team_change,
)
from litellm.proxy.proxy_server import app
from litellm.types.proxy.management_endpoints.key_management_endpoints import (
    BulkUpdateKeyRequest,
    BulkUpdateKeyResponse,
    CustomKeyPolicyRequest,
)

client = TestClient(app)


@pytest.mark.asyncio
async def test_list_keys():
    mock_prisma_client = AsyncMock()
    mock_find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many
    args = {
        "prisma_client": mock_prisma_client,
        "page": 1,
        "size": 50,
        "user_id": "cda88cb4-cc2c-4e8c-b871-dc71ca111b00",
        "team_id": None,
        "organization_id": None,
        "key_alias": None,
        "key_hash": None,
        "exclude_team_id": None,
        "return_full_object": True,
        "admin_team_ids": ["28bd3181-02c5-48f2-b408-ce790fb3d5ba"],
    }
    try:
        result = await list_key_helper(**args)
    except Exception as e:
        print(f"error: {e}")

    mock_find_many.assert_called_once()

    where_condition = mock_find_many.call_args.kwargs["where"]
    print(f"where_condition: {where_condition}")
    assert json.dumps({"team_id": {"not": "litellm-dashboard"}}) in json.dumps(
        where_condition
    )


@pytest.mark.asyncio
async def test_list_keys_include_created_by_keys():
    """
    Test that include_created_by_keys parameter correctly includes keys created by the user
    and applies specific filtering to both user's own keys and created_by keys.
    """
    mock_prisma_client = AsyncMock()
    mock_find_many = AsyncMock(return_value=[])
    mock_count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many
    mock_prisma_client.db.litellm_verificationtoken.count = mock_count

    test_user_id = "user-123"
    test_org_id = "org-456"
    test_key_alias = "test-alias"
    test_key_hash = "hashed-token-789"

    # Test Case 1: include_created_by_keys=True with specific filters
    args = {
        "prisma_client": mock_prisma_client,
        "page": 1,
        "size": 50,
        "user_id": test_user_id,
        "team_id": None,
        "organization_id": test_org_id,
        "key_alias": test_key_alias,
        "key_hash": test_key_hash,
        "exclude_team_id": None,
        "return_full_object": True,
        "admin_team_ids": None,
        "include_created_by_keys": True,
    }

    try:
        result = await list_key_helper(**args)
    except Exception as e:
        print(f"error: {e}")

    mock_find_many.assert_called_once()
    mock_count.assert_called_once()

    where_condition = mock_find_many.call_args.kwargs["where"]
    print(f"where_condition with include_created_by_keys=True: {where_condition}")

    def _flatten_and(node):
        if set(node.keys()) == {"AND"}:
            return [c for child in node["AND"] for c in _flatten_and(child)]
        return [node]

    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)
    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

    # First condition should be user's own keys with all filters applied
    user_condition = None
    created_by_condition = None

    for condition in or_conditions:
        if "user_id" in condition:
            user_condition = condition
        elif "created_by" in condition:
            created_by_condition = condition

    assert user_condition is not None, "User condition should be present"
    assert created_by_condition is not None, "Created by condition should be present"

    assert user_condition["user_id"] == test_user_id
    assert user_condition["organization_id"] == test_org_id
    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
    assert created_by_condition["created_by"] == test_user_id
    assert (
        len(created_by_condition) == 1
    ), "Created by condition should only have created_by field"

    # Reset mocks for Test Case 2
    mock_find_many.reset_mock()
    mock_count.reset_mock()

    # Test Case 2: include_created_by_keys=False should not include created_by condition
    args["include_created_by_keys"] = False

    try:
        result = await list_key_helper(**args)
    except Exception as e:
        print(f"error: {e}")

    where_condition_no_created_by = mock_find_many.call_args.kwargs["where"]
    print(
        f"where_condition with include_created_by_keys=False: {where_condition_no_created_by}"
    )

    # Should not have OR conditions when include_created_by_keys=False and no admin_team_ids
    # The user condition should be merged directly into the where clause
    assert "created_by" not in json.dumps(where_condition_no_created_by)

    # Reset mocks for Test Case 3
    mock_find_many.reset_mock()
    mock_count.reset_mock()

    # Test Case 3: include_created_by_keys=True with exclude_team_id
    args.update(
        {
            "include_created_by_keys": True,
            "exclude_team_id": "excluded-team-123",
            "team_id": None,  # Make sure no specific team is set
        }
    )

    try:
        result = await list_key_helper(**args)
    except Exception as e:
        print(f"error: {e}")

    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 = _find_visibility_or(where_condition_with_exclude)

    # Find the user condition and created_by condition
    user_condition_with_exclude = None
    created_by_condition_with_exclude = None

    for condition in or_conditions_with_exclude:
        if "user_id" in condition:
            user_condition_with_exclude = condition
        elif "created_by" in condition:
            created_by_condition_with_exclude = condition

    # Verify exclude_team_id is applied to user condition
    assert (
        user_condition_with_exclude is not None
    ), "User condition with exclude should be present"
    assert user_condition_with_exclude["team_id"] == {"not": "excluded-team-123"}

    # Verify created_by condition still only has created_by filter
    assert (
        created_by_condition_with_exclude is not None
    ), "Created by condition with exclude should be present"
    assert created_by_condition_with_exclude["created_by"] == test_user_id
    assert len(created_by_condition_with_exclude) == 1


@pytest.mark.asyncio
async def test_key_token_handling(monkeypatch):
    """
    Test that token handling in key generation follows the expected behavior:
    1. token field should not equal key field
    2. if token_id exists, it should equal token field
    """
    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )
    from litellm.proxy.proxy_server import prisma_client

    # Use monkeypatch to set the prisma_client
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Test key generation
    response = await generate_key_fn(
        data=GenerateKeyRequest(),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876", user_id="1234"
        ),
    )

    # Verify token handling
    assert response.key != response.token, "Token should not equal key"
    if hasattr(response, "token_id"):
        assert (
            response.token == response.token_id
        ), "Token should equal token_id if token_id exists"


@pytest.mark.asyncio
async def test_budget_reset_and_expires_at_first_of_month(monkeypatch):
    """
    Test that when budget_duration, duration, and key_budget_duration are "1mo":
    - budget_reset_at is set to first of next month (standardized reset time)
    - expires is set to approximately 1 month from creation time (exact duration)
    """
    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None)
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None)
    )

    from datetime import datetime, timedelta, timezone

    import pytest

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_helper_fn,
    )
    from litellm.proxy.proxy_server import prisma_client

    # Use monkeypatch to set the prisma_client
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Test key generation with budget_duration="1mo", duration="1mo", key_budget_duration="1mo"
    response = await generate_key_helper_fn(
        request_type="user",
        budget_duration="1mo",
        duration="1mo",
        key_budget_duration="1mo",
        user_id="test_user",
    )

    print(f"response: {response}\n")
    # Get the current date
    now = datetime.now(timezone.utc)

    # Calculate expected reset date (first of next month) for budget_reset_at
    if now.month == 12:
        expected_month = 1
        expected_year = now.year + 1
    else:
        expected_month = now.month + 1
        expected_year = now.year

    # Verify budget_reset_at is set to first of next month (standardized reset time)
    budget_reset_at = response.get("budget_reset_at")
    assert budget_reset_at is not None, "budget_reset_at not found in response"
    assert (
        budget_reset_at.year == expected_year
    ), f"Expected year {expected_year}, got {budget_reset_at.year} for budget_reset_at"
    assert (
        budget_reset_at.month == expected_month
    ), f"Expected month {expected_month}, got {budget_reset_at.month} for budget_reset_at"
    assert (
        budget_reset_at.day == 1
    ), f"Expected day 1, got {budget_reset_at.day} for budget_reset_at"

    # Verify expires is set to approximately 1 month from creation time (exact duration, not standardized)
    expires = response.get("expires")
    assert expires is not None, "expires not found in response"
    # expires should be approximately 1 month from now (same day next month, same time)
    # Allow for some variance due to test execution time (subtract 1 second buffer for timing)
    expected_expires_min = now + timedelta(days=28, seconds=-1)
    expected_expires_max = now + timedelta(days=32)
    assert (
        expected_expires_min <= expires <= expected_expires_max
    ), f"Expected expires to be approximately 1 month from now, got {expires}"


@pytest.mark.asyncio
async def test_key_expiration_exact_duration_hours(monkeypatch):
    """
    Test that key expiration uses exact duration addition, not standardized reset times.
    Specifically tests the bug where "12h" duration would expire at midnight instead of 12 hours from creation.
    """
    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None)
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None)
    )

    from datetime import datetime, timedelta, timezone

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_helper_fn,
    )

    # Use monkeypatch to set the prisma_client
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Test key generation with duration="12h"
    # This should expire exactly 12 hours from creation, not at the next midnight/noon boundary
    response = await generate_key_helper_fn(
        request_type="user",
        duration="12h",
        user_id="test_user",
    )

    expires = response.get("expires")
    assert expires is not None, "expires not found in response"

    # Calculate expected expiration (approximately 12 hours from now)
    # Allow for small variance due to test execution time
    now = datetime.now(timezone.utc)
    expected_expires_min = now + timedelta(hours=11, minutes=59)
    expected_expires_max = now + timedelta(hours=12, minutes=1)

    assert (
        expected_expires_min <= expires <= expected_expires_max
    ), f"Expected expires to be approximately 12 hours from now ({now}), got {expires}. Duration should be exact, not aligned to time boundaries."

    # Verify it's NOT aligned to hour boundaries (e.g., not exactly at :00 minutes)
    # If created at 2:30 PM, it should expire at 2:30 AM, not midnight
    expires_minute = expires.minute
    expires_second = expires.second
    # If the expiration is exactly at :00:00, it might be aligned (though could be coincidence)
    # More importantly, verify the duration is correct
    time_diff = expires - now
    hours_diff = time_diff.total_seconds() / 3600
    assert (
        11.9 <= hours_diff <= 12.1
    ), f"Expected expiration to be approximately 12 hours from creation, got {hours_diff} hours"


@pytest.mark.asyncio
async def test_generate_key_persists_tpd_limit(monkeypatch):
    mock_prisma_client = AsyncMock()
    mock_prisma_client.insert_data = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None)
    )
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data_json = GenerateKeyRequest(tpd_limit=250000, rpm_limit=5).model_dump(exclude_none=True)
    response = await generate_key_helper_fn(request_type="key", **data_json, table_name="key")

    assert response["tpd_limit"] == 250000
    key_insert = mock_prisma_client.insert_data.await_args_list[-1].kwargs
    assert key_insert["table_name"] == "key"
    assert key_insert["data"]["tpd_limit"] == 250000
    assert key_insert["data"]["rpm_limit"] == 5


@pytest.mark.asyncio
async def test_key_generation_with_object_permission(monkeypatch):
    """Ensure /key/generate correctly handles `object_permission` input by
    1. Creating a record in litellm_objectpermissiontable
    2. Passing the returned `object_permission_id` into the key insert payload
    """
    # --- Setup mocked prisma client ---
    mock_prisma_client = AsyncMock()

    # identity helper for jsonify_object (used inside generate_key_helper_fn)
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore

    # Mock the prisma_client.db.litellm_objectpermissiontable.create call
    mock_object_permission_create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm123")
    )
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = (
        mock_object_permission_create
    )

    # Mock prisma_client.insert_data for both user and key tables
    async def _insert_data_side_effect(*args, **kwargs):  # type: ignore
        table_name = kwargs.get("table_name")
        if table_name == "user":
            # minimal attributes accessed later in generate_key_helper_fn
            return MagicMock(models=[], spend=0)
        elif table_name == "key":
            return MagicMock(
                token="hashed_token_456",
                litellm_budget_table=None,
                object_permission=None,
            )
        return MagicMock()

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)

    # Attach the mocked prisma client to the proxy_server module
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # --- Import objects after monkeypatching ---
    from litellm.proxy._types import (
        GenerateKeyRequest,
        LiteLLM_ObjectPermissionBase,
        LitellmUserRoles,
    )
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    # --- Call generate_key_fn with object_permission ---
    request_data = GenerateKeyRequest(
        object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["my-vector"])
    )

    await generate_key_fn(
        data=request_data,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="user-1",
        ),
    )

    # --- Assertions ---
    # 1. Object permission creation was triggered
    mock_object_permission_create.assert_called_once()

    # 2. Key insert received the generated object_permission_id
    key_insert_calls = [
        call.kwargs
        for call in mock_prisma_client.insert_data.call_args_list
        if call.kwargs.get("table_name") == "key"
    ]
    assert len(key_insert_calls) == 1
    assert key_insert_calls[0]["data"].get("object_permission_id") == "objperm123"


@pytest.mark.asyncio
async def test_generate_key_debug_log_never_contains_raw_token(monkeypatch, caplog):
    """Regression for LIT-4356: /key/generate must never emit the raw virtual key
    to a logger, even for short keys that bypass the regex-based
    SecretRedactionFilter."""
    import hashlib
    import logging

    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    mock_prisma_client.db = MagicMock()

    async def _insert_data_side_effect(*args, **kwargs):
        if kwargs.get("table_name") == "user":
            return MagicMock(models=[], spend=0)
        return MagicMock(
            token="hashed_token_456",
            litellm_budget_table=None,
            object_permission=None,
        )

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    raw_key = "sk-short-secret-a1b2"
    with caplog.at_level(logging.DEBUG, logger="LiteLLM Proxy"):
        await generate_key_fn(
            data=GenerateKeyRequest(key=raw_key),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-9876",
                user_id="user-1",
            ),
        )

    log_text = "\n".join(record.getMessage() for record in caplog.records)
    assert raw_key not in log_text
    assert hashlib.sha256(raw_key.encode()).hexdigest() in log_text


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "field,request_kwargs,expected_in_error",
    [
        (
            "access_group_ids",
            {"access_group_ids": ["acme_private"]},
            "Access groups",
        ),
        (
            "mcp_toolsets",
            {"object_permission": {"mcp_toolsets": ["acme_toolset"]}},
            "MCP toolsets",
        ),
        (
            "vector_stores",
            {"object_permission": {"vector_stores": ["acme_vs"]}},
            "Vector stores",
        ),
        (
            "search_tools",
            {"object_permission": {"search_tools": ["acme_search"]}},
            "search_tools",
        ),
    ],
)
async def test_generate_key_personal_non_admin_denied_for_team_scoped_fields(
    monkeypatch, field, request_kwargs, expected_in_error
):
    """generate_key_fn must reject access_group_ids and
    object_permission.{mcp_toolsets, vector_stores, search_tools} when the
    caller is a non-admin and the request has no team_id. Mutating any of the
    three validator calls in _common_key_generation_helper or unmoving the
    enforce_member_can_assign_access_groups call in _personal_key_generation_check
    must break this test."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id="should-not-create")
    )
    mock_prisma_client.insert_data = AsyncMock(return_value=MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    from litellm.proxy._types import (
        GenerateKeyRequest,
        LiteLLM_ObjectPermissionBase,
        LitellmUserRoles,
    )
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    if "object_permission" in request_kwargs:
        request_kwargs = {
            **request_kwargs,
            "object_permission": LiteLLM_ObjectPermissionBase(
                **request_kwargs["object_permission"]
            ),
        }
    request_data = GenerateKeyRequest(**request_kwargs)

    from litellm.proxy._types import ProxyException

    with pytest.raises((HTTPException, ProxyException)) as exc:
        await generate_key_fn(
            data=request_data,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-alice",
                user_id="alice",
            ),
        )
    code = getattr(exc.value, "status_code", None) or getattr(exc.value, "code", None)
    assert int(code) == 403
    body = str(
        getattr(exc.value, "detail", None) or getattr(exc.value, "message", exc.value)
    )
    assert expected_in_error in body
    mock_prisma_client.db.litellm_objectpermissiontable.create.assert_not_called()


@pytest.mark.asyncio
async def test_update_key_personal_non_admin_denied_vector_stores(monkeypatch):
    """/key/update must reject vector_stores on a personal key by a non-admin.
    Reverting the enforce_member_can_assign_access_groups move (i.e. putting
    it back inside `if _team_id_to_check is not None`) does NOT cover
    object_permission fields; this test exercises _validate_update_key_data
    which calls _validate_mcp_servers_for_key_update."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore
    mock_prisma_client.db = MagicMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache",
        MagicMock(),
    )

    from litellm.proxy._types import (
        LiteLLM_ObjectPermissionBase,
        LitellmUserRoles,
        UpdateKeyRequest,
    )
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _validate_update_key_data,
    )

    existing_key_row = MagicMock(
        token="hashed_alice_personal_key",
        user_id="alice",
        team_id=None,
        created_by="alice",
        max_budget=None,
        organization_id=None,
        project_id=None,
    )
    data = UpdateKeyRequest(
        key="sk-alice-personal",
        object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["acme_vs"]),
    )

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=existing_key_row,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-alice",
                user_id="alice",
            ),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "Vector stores" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_grandfathers_existing_mcp_servers(monkeypatch):
    """/key/update on a team key that already holds MCP servers outside the
    team allowlist must accept re-sent or shrunk grants (LIT-6062). The wrapper
    must pass the existing key's object_permission row into the validator when
    the team is unchanged."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import (
        LiteLLM_ObjectPermissionBase,
        UpdateKeyRequest,
    )
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _validate_mcp_servers_for_key_update,
    )

    existing_row = MagicMock()
    existing_row.mcp_servers = ["server-a", "server-b"]
    existing_row.mcp_tool_permissions = {}
    mock_prisma = MagicMock()
    mock_prisma.db.litellm_mcpservertable.find_many = AsyncMock(return_value=[])

    team_obj = MagicMock()
    team_obj.team_id = "team-1"
    team_obj.object_permission = None

    existing_key_row = MagicMock(
        team_id="team-1",
        object_permission_id="perm-1",
        object_permission=existing_row,
    )

    mock_server_a = MagicMock()
    mock_server_a.server_id = "server-a"
    mock_server_b = MagicMock()
    mock_server_b.server_id = "server-b"
    mock_mgr = MagicMock()
    mock_mgr.get_registry.return_value = {
        "server-a": mock_server_a,
        "server-b": mock_server_b,
    }
    mock_mgr.get_allow_all_keys_server_ids.return_value = []
    monkeypatch.setattr(
        "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
        mock_mgr,
    )

    result = await _validate_mcp_servers_for_key_update(
        data=UpdateKeyRequest(
            key="sk-team-key",
            object_permission=LiteLLM_ObjectPermissionBase(mcp_servers=["server-a"]),
        ),
        team_obj=team_obj,
        existing_key_row=existing_key_row,
        prisma_client=mock_prisma,
        user_api_key_cache=MagicMock(),
        is_proxy_admin=False,
    )
    assert result is not None
    assert result["mcp_servers"] == ["server-a"]


@pytest.mark.asyncio
async def test_update_key_personal_non_admin_denied_access_groups(
    monkeypatch,
):
    """/key/update on a personal key must also gate access_group_ids for
    non-admins. Reverting the enforce move (putting it back inside
    `if _team_id_to_check is not None`) breaks this test."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    from litellm.proxy._types import LitellmUserRoles, UpdateKeyRequest
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _validate_update_key_data,
    )

    existing_key_row = MagicMock(
        token="hashed_alice_personal_key",
        user_id="alice",
        team_id=None,
        created_by="alice",
        max_budget=None,
        organization_id=None,
        project_id=None,
    )
    data = UpdateKeyRequest(
        key="sk-alice-personal",
        access_group_ids=["ag-private"],
    )

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=existing_key_row,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-alice",
                user_id="alice",
            ),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "Access groups" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_generate_key_helper_fn_with_access_group_ids(monkeypatch):
    """Ensure generate_key_helper_fn passes access_group_ids into the key insert payload."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id=None)
    )
    mock_prisma_client.db.query_raw = AsyncMock(return_value=[])

    captured_key_data = {}

    async def _insert_data_side_effect(*args, **kwargs):
        table_name = kwargs.get("table_name")
        if table_name == "user":
            return MagicMock(models=[], spend=0)
        elif table_name == "key":
            captured_key_data.update(kwargs.get("data", {}))
            return MagicMock(
                token="hashed_token_789",
                litellm_budget_table=None,
                object_permission=None,
                created_at=None,
                updated_at=None,
            )
        return MagicMock()

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_helper_fn,
    )

    await generate_key_helper_fn(
        request_type="key",
        table_name="key",
        user_id="test-user",
        access_group_ids=["ag-1", "ag-2"],
    )

    assert captured_key_data.get("access_group_ids") == ["ag-1", "ag-2"]


@pytest.mark.asyncio
async def test_generate_key_helper_fn_with_budget_fallbacks(monkeypatch):
    """Regression: /key/generate must accept `budget_fallbacks` end-to-end.

    generate_key_helper_fn previously had no `budget_fallbacks` parameter, so
    passing it via /key/generate (which unpacks the full request body as
    kwargs) raised "unexpected keyword argument" before ever reaching the DB.
    """
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data  # type: ignore
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id=None)
    )

    captured_key_data = {}

    async def _insert_data_side_effect(*args, **kwargs):
        table_name = kwargs.get("table_name")
        if table_name == "user":
            return MagicMock(models=[], spend=0)
        elif table_name == "key":
            captured_key_data.update(kwargs.get("data", {}))
            return MagicMock(
                token="hashed_token_budget_fallbacks",
                litellm_budget_table=None,
                object_permission=None,
                created_at=None,
                updated_at=None,
            )
        return MagicMock()

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_helper_fn,
    )

    await generate_key_helper_fn(
        request_type="key",
        table_name="key",
        user_id="test-user",
        budget_fallbacks={"anthropic-haiku-4-5": ["gpt-5.5"]},
    )

    assert json.loads(captured_key_data["budget_fallbacks"]) == {
        "anthropic-haiku-4-5": ["gpt-5.5"]
    }


@pytest.mark.asyncio
async def test_key_generation_with_mcp_tool_permissions(monkeypatch):
    """
    Test that /key/generate correctly handles mcp_tool_permissions in object_permission.

    This test verifies that:
    1. mcp_tool_permissions is accepted in the object_permission field
    2. The field is properly stored in the LiteLLM_ObjectPermissionTable
    3. The key is correctly linked to the object_permission record
    """
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data

    # Track what data is passed to create
    created_permission_data = {}

    async def mock_create(**kwargs):
        created_permission_data.update(kwargs.get("data", {}))
        return MagicMock(object_permission_id="objperm_mcp_123")

    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = mock_create
    mock_prisma_client.db.litellm_mcpservertable.find_many = AsyncMock(return_value=[])

    async def _insert_data_side_effect(*args, **kwargs):
        table_name = kwargs.get("table_name")
        if table_name == "user":
            return MagicMock(models=[], spend=0)
        elif table_name == "key":
            return MagicMock(
                token="hashed_token_789",
                litellm_budget_table=None,
                object_permission=None,
            )
        return MagicMock()

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_mcp_servers_against_team",
        AsyncMock(
            side_effect=lambda object_permission=None, **kwargs: object_permission
        ),
    )

    from litellm.proxy._types import (
        GenerateKeyRequest,
        LiteLLM_ObjectPermissionBase,
        LitellmUserRoles,
    )
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    # Create request with mcp_tool_permissions
    request_data = GenerateKeyRequest(
        object_permission=LiteLLM_ObjectPermissionBase(
            mcp_servers=["server_1"],
            mcp_tool_permissions={"server_1": ["tool1", "tool2", "tool3"]},
        )
    )

    await generate_key_fn(
        data=request_data,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="user-mcp-1",
        ),
    )

    # Verify mcp_tool_permissions was stored (serialized to JSON string for GraphQL compatibility)
    assert "mcp_tool_permissions" in created_permission_data
    import json

    assert json.loads(created_permission_data["mcp_tool_permissions"]) == {
        "server_1": ["tool1", "tool2", "tool3"]
    }
    assert created_permission_data["mcp_servers"] == ["server_1"]


@pytest.mark.asyncio
async def test_key_update_prepares_existing_object_permission_without_writing():
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_ObjectPermissionBase, LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _prepare_key_update_object_permission,
        _write_prepared_key_update_object_permission,
    )

    mock_prisma_client = AsyncMock()
    existing_key_row = LiteLLM_VerificationToken(
        token="test_token_hash",
        object_permission_id="existing_perm_id_123",
        user_id="user123",
        team_id=None,
    )
    existing_permission = MagicMock()
    existing_permission.model_dump.return_value = {
        "object_permission_id": "existing_perm_id_123",
        "vector_stores": ["old_store"],
    }
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=existing_permission)
    permission_upsert = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert

    object_permission_data = LiteLLM_ObjectPermissionBase(vector_stores=["new_store"]).model_dump(
        exclude_unset=True, exclude_none=True
    )
    upsert = await _prepare_key_update_object_permission(
        object_permission_data=object_permission_data,
        existing_key_row=existing_key_row,
        prisma_client=mock_prisma_client,
    )

    assert upsert is not None
    assert upsert.object_permission_id == "existing_perm_id_123"
    assert upsert.record["vector_stores"] == ["new_store"]
    permission_upsert.assert_not_awaited()
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique.assert_awaited_once_with(
        where={"object_permission_id": "existing_perm_id_123"}
    )

    result = await _write_prepared_key_update_object_permission(
        data_json={"user_id": "user123"},
        upsert=upsert,
        prisma_client=mock_prisma_client,
    )

    assert result == {"user_id": "user123", "object_permission_id": "existing_perm_id_123"}
    permission_upsert.assert_awaited_once_with(
        where={"object_permission_id": "existing_perm_id_123"},
        data={"create": upsert.record, "update": upsert.record},
    )


@pytest.mark.asyncio
async def test_key_update_prepares_json_object_permission_and_upserts_new_row():
    import json
    from unittest.mock import AsyncMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _prepare_key_update_object_permission,
        _write_prepared_key_update_object_permission,
    )

    mock_prisma_client = AsyncMock()
    existing_key_row = LiteLLM_VerificationToken(
        token="test_token_hash_2",
        object_permission_id=None,
        user_id="user456",
        team_id=None,
    )
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=None)
    permission_upsert = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert

    upsert = await _prepare_key_update_object_permission(
        object_permission_data=json.dumps({"vector_stores": ["brand_new_store"]}),
        existing_key_row=existing_key_row,
        prisma_client=mock_prisma_client,
    )

    assert upsert is not None
    assert upsert.record["vector_stores"] == ["brand_new_store"]
    permission_upsert.assert_not_awaited()
    result = await _write_prepared_key_update_object_permission(
        data_json={},
        upsert=upsert,
        prisma_client=mock_prisma_client,
    )

    assert result["object_permission_id"] == upsert.object_permission_id
    permission_upsert.assert_awaited_once_with(
        where={"object_permission_id": upsert.object_permission_id},
        data={"create": upsert.record, "update": upsert.record},
    )


@pytest.mark.asyncio
async def test_key_update_recreates_missing_object_permission_with_existing_id():
    from unittest.mock import AsyncMock

    from litellm.proxy._types import LiteLLM_ObjectPermissionBase, LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _prepare_key_update_object_permission,
        _write_prepared_key_update_object_permission,
    )

    mock_prisma_client = AsyncMock()
    existing_key_row = LiteLLM_VerificationToken(
        token="test_token_hash_3",
        object_permission_id="missing_perm_id_789",
        user_id="user789",
        team_id=None,
    )
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=None)
    permission_upsert = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert

    upsert = await _prepare_key_update_object_permission(
        object_permission_data=LiteLLM_ObjectPermissionBase(vector_stores=["recreated_store"]).model_dump(
            exclude_unset=True, exclude_none=True
        ),
        existing_key_row=existing_key_row,
        prisma_client=mock_prisma_client,
    )

    assert upsert is not None
    assert upsert.object_permission_id == "missing_perm_id_789"
    permission_upsert.assert_not_awaited()
    await _write_prepared_key_update_object_permission(
        data_json={},
        upsert=upsert,
        prisma_client=mock_prisma_client,
    )
    permission_upsert.assert_awaited_once_with(
        where={"object_permission_id": "missing_perm_id_789"},
        data={"create": upsert.record, "update": upsert.record},
    )


@pytest.mark.asyncio
async def test_key_update_object_permission_does_not_add_null_fields():
    """
    Updating a key with an object_permission that only sets a subset of fields
    must not normalize the unset list fields to ``None``.

    The UI always submits object_permission with empty MCP/vector lists, even for
    a TPM/RPM-only edit. ``models``/``blocked_tools``/``search_tools`` are
    non-nullable array columns, so emitting them as ``None`` makes the downstream
    Prisma write fail. The normalized object_permission must keep the same field
    set the caller provided.
    """
    data = UpdateKeyRequest(
        key="sk-test-key",
        tpm_limit=123,
        rpm_limit=456,
        object_permission={
            "vector_stores": [],
            "mcp_servers": [],
            "mcp_access_groups": [],
            "mcp_toolsets": [],
            "agents": [],
            "agent_access_groups": [],
        },
    )
    provided_fields = set(data.object_permission.model_fields_set)

    existing_key_row = MagicMock()
    existing_key_row.user_id = "admin_user"
    existing_key_row.token = "hashed_token"
    existing_key_row.team_id = None
    existing_key_row.organization_id = None
    existing_key_row.project_id = None

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin_user",
    )

    await _validate_update_key_data(
        data=data,
        existing_key_row=existing_key_row,
        user_api_key_dict=user_api_key_dict,
        llm_router=None,
        premium_user=False,
        prisma_client=AsyncMock(),
        user_api_key_cache=MagicMock(),
    )

    normalized = data.object_permission.model_dump(exclude_unset=True)
    assert set(normalized.keys()) == provided_fields
    assert "models" not in normalized
    assert "blocked_tools" not in normalized
    assert "search_tools" not in normalized
    assert "mcp_tool_permissions" not in normalized


@pytest.mark.asyncio
async def test_key_info_returns_object_permission(monkeypatch):
    """
    Test that /key/info correctly returns the object_permission relation.

    This test verifies that when calling /key/info for a key with object_permission_id,
    the response includes the full object_permission object with fields like
    mcp_access_groups, mcp_servers, vector_stores, agents, etc.

    Regression test for bug where object_permission_id was returned but not the
    related object_permission object.
    """
    from unittest.mock import AsyncMock, MagicMock

    import pytest

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    # Mock prisma client
    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Mock key with object_permission_id
    test_key_token = "hashed_test_token_123"
    test_object_permission_id = "objperm_info_test_123"

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = test_object_permission_id
    mock_key_info.user_id = "user123"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None

    # Mock the dict/model_dump methods
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "object_permission_id": test_object_permission_id,
        "user_id": "user123",
        "team_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    # Mock find_unique for the key lookup
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )

    # Mock object permission record
    mock_object_permission = MagicMock()
    mock_object_permission.model_dump.return_value = {
        "object_permission_id": test_object_permission_id,
        "mcp_access_groups": ["test_group_1", "test_group_2"],
        "mcp_servers": ["server_1"],
        "vector_stores": ["vs_1", "vs_2"],
        "agents": ["agent_1"],
    }
    mock_object_permission.dict.return_value = (
        mock_object_permission.model_dump.return_value
    )

    # Mock find_unique for object permission lookup
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(
        return_value=mock_object_permission
    )

    # Create user API key dict
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-key-456",
    )

    # Call info_key_fn
    result = await info_key_fn(
        key="sk-test-key-456",
        user_api_key_dict=user_api_key_dict,
    )

    # Assertions
    assert "info" in result
    assert "object_permission_id" in result["info"]
    assert result["info"]["object_permission_id"] == test_object_permission_id

    # CRITICAL: Verify that object_permission object is included in response
    assert "object_permission" in result["info"], (
        "object_permission field missing from /key/info response. "
        "Expected full object_permission object to be attached."
    )

    # Verify object_permission contains the expected fields
    obj_perm = result["info"]["object_permission"]
    assert obj_perm["object_permission_id"] == test_object_permission_id
    assert obj_perm["mcp_access_groups"] == ["test_group_1", "test_group_2"]
    assert obj_perm["mcp_servers"] == ["server_1"]
    assert obj_perm["vector_stores"] == ["vs_1", "vs_2"]
    assert obj_perm["agents"] == ["agent_1"]

    # Verify the object permission was actually queried from database
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique.assert_called_once_with(
        where={"object_permission_id": test_object_permission_id}
    )


def _stored_key_with_lifetime_spend(token: str, spend: float, total_spend: float) -> LiteLLM_VerificationToken:
    return LiteLLM_VerificationToken.model_validate(
        {"token": token, "user_id": "user123", "spend": spend, "total_spend": total_spend}
    )


@pytest.mark.asyncio
async def test_key_info_returns_lifetime_total_spend_next_to_resettable_spend(monkeypatch):
    """After a budget reset the period spend is 0 while total_spend keeps the lifetime figure."""
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=_stored_key_with_lifetime_spend(token="hashed_key", spend=0.0, total_spend=3.75)
    )

    result = await info_key_fn(
        key="sk-test-key-456",
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-test-key-456"),
    )

    assert result["info"]["spend"] == 0.0
    assert result["info"]["total_spend"] == 3.75


@pytest.mark.asyncio
async def test_list_keys_full_object_returns_lifetime_total_spend():
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[_stored_key_with_lifetime_spend(token="hashed_key", spend=0.0, total_spend=3.75)]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=1)

    result = await list_key_helper(
        prisma_client=mock_prisma_client,
        page=1,
        size=50,
        user_id=None,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        return_full_object=True,
        admin_team_ids=None,
    )

    listed_key = result["keys"][0]
    assert isinstance(listed_key, UserAPIKeyAuth)
    assert listed_key.spend == 0.0
    assert listed_key.total_spend == 3.75


@pytest.mark.asyncio
async def test_get_new_token_with_valid_key(monkeypatch):
    """Test get_new_token function when provided with a valid key that starts with 'sk-'"""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_new_token,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    # Test with valid new_key
    data = RegenerateKeyRequest(new_key="sk-test1234567890abc")
    result = await get_new_token(data)

    assert result == "sk-test1234567890abc"


@pytest.mark.asyncio
async def test_get_new_token_with_invalid_key(monkeypatch):
    """Test get_new_token function when provided with an invalid key that doesn't start with 'sk-'"""
    from fastapi import HTTPException

    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_new_token,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    # Test with invalid new_key (doesn't start with 'sk-')
    data = RegenerateKeyRequest(new_key="invalid-key-123")

    with pytest.raises(HTTPException) as exc_info:
        await get_new_token(data)

    assert exc_info.value.status_code == 400
    assert "New key must start with 'sk-'" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_get_new_token_rejects_short_new_key(monkeypatch):
    """Regression test for LIT-4355: a short custom key like sk-99 must be rejected,
    otherwise the stored key_name (sk-...{last 4 chars}) reveals the entire key."""
    from fastapi import HTTPException

    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_new_token,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    data = RegenerateKeyRequest(new_key="sk-99")

    with pytest.raises(HTTPException) as exc_info:
        await get_new_token(data)

    assert exc_info.value.status_code == 400
    assert "at least 16 characters" in str(exc_info.value.detail)


@pytest.mark.asyncio
@pytest.mark.parametrize("short_key", ["sk-9876", "sk-abcdefghijkl"])
async def test_generate_key_fn_rejects_short_custom_key(monkeypatch, short_key):
    """Regression test for LIT-4355: /key/generate must reject custom keys shorter
    than the minimum length (including the 15-char boundary); sk-9876 used to be
    accepted and fully exposed via key_name."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles, ProxyException
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    assert len(short_key) < 16

    with pytest.raises(ProxyException) as exc_info:
        await generate_key_fn(
            data=GenerateKeyRequest(key=short_key),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876", user_id="1234"
            ),
        )

    assert exc_info.value.code == "400"
    assert "at least 16 characters" in str(exc_info.value.message)


@pytest.mark.asyncio
async def test_generate_key_fn_accepts_custom_key_at_minimum_length(monkeypatch):
    """Custom keys at exactly the minimum length (16 chars) are still accepted."""
    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None, object_permission=None)
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    custom_key = "sk-abcdefghijklm"
    assert len(custom_key) == 16

    response = await generate_key_fn(
        data=GenerateKeyRequest(key=custom_key),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876", user_id="1234"
        ),
    )

    assert response.key == custom_key


@pytest.mark.asyncio
async def test_check_custom_key_allowed_when_disabled(monkeypatch):
    """_check_custom_key_allowed raises 403 when disable_custom_api_keys is true."""
    from fastapi import HTTPException

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {"disable_custom_api_keys": True})

    with pytest.raises(HTTPException) as exc_info:
        await _check_custom_key_allowed("sk-custom-key-123")

    assert exc_info.value.status_code == 403
    assert "disabled" in str(exc_info.value.detail).lower()


@pytest.mark.asyncio
async def test_check_custom_key_allowed_when_enabled(monkeypatch):
    """_check_custom_key_allowed does nothing when disable_custom_api_keys is false."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {"disable_custom_api_keys": False})

    # Should not raise
    await _check_custom_key_allowed("sk-custom-key-123")


@pytest.mark.asyncio
async def test_check_custom_key_allowed_when_unset(monkeypatch):
    """_check_custom_key_allowed does nothing when setting is not present."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {})

    # Should not raise
    await _check_custom_key_allowed("sk-custom-key-123")


@pytest.mark.asyncio
async def test_check_custom_key_allowed_honours_the_config_file(monkeypatch):
    """A config-file general_settings.disable_custom_api_keys is enforced with no stored UI row."""
    from fastapi import HTTPException

    from litellm.proxy.config_resolvers import SettingsStore
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    general_settings = SettingsStore("general_settings")
    general_settings.load_yaml({"disable_custom_api_keys": True})
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", general_settings)

    with pytest.raises(HTTPException) as exc_info:
        await _check_custom_key_allowed("sk-custom-key-123456")

    assert exc_info.value.status_code == 403


@pytest.mark.parametrize(
    ("config_value", "blocked"),
    [
        (True, True),
        ("true", True),
        ("True", True),
        (1, True),
        (False, False),
        ("false", False),
        ("False", False),
        (0, False),
    ],
)
@pytest.mark.asyncio
async def test_check_custom_key_allowed_coerces_a_non_bool_config_value(monkeypatch, config_value, blocked):
    """A YAML value that is not a bare bool, such as a quoted "true", still decides the gate."""
    from fastapi import HTTPException

    from litellm.proxy.config_resolvers import SettingsStore
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    general_settings = SettingsStore("general_settings")
    general_settings.load_yaml({"disable_custom_api_keys": config_value})
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", general_settings)

    rejected = False
    try:
        await _check_custom_key_allowed("sk-custom-key-123456")
    except HTTPException as e:
        rejected = e.status_code == 403

    assert rejected is blocked


@pytest.mark.asyncio
async def test_check_custom_key_allowed_config_file_beats_the_stored_ui_row(monkeypatch):
    """The config file owns the flag, so a stored UI row saying false cannot re-open custom keys."""
    from fastapi import HTTPException

    from litellm.proxy.config_resolvers import SettingsStore
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )
    from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
        apply_runtime_general_settings_flags,
    )

    general_settings = SettingsStore("general_settings")
    general_settings.load_yaml({"disable_custom_api_keys": True})
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", general_settings)

    apply_runtime_general_settings_flags({"disable_custom_api_keys": False})

    with pytest.raises(HTTPException) as exc_info:
        await _check_custom_key_allowed("sk-custom-key-123456")

    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_check_custom_key_allowed_picks_up_a_ui_write_without_the_serving_pod(monkeypatch):
    """A pod that never served the PATCH enforces the new value after its own settings sync."""
    from fastapi import HTTPException

    from litellm.proxy.config_resolvers import SettingsStore
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )
    from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
        apply_runtime_general_settings_flags,
    )

    general_settings = SettingsStore("general_settings")
    general_settings.load_yaml({})
    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", general_settings)

    await _check_custom_key_allowed("sk-custom-key-123456")

    apply_runtime_general_settings_flags({"disable_custom_api_keys": True})

    with pytest.raises(HTTPException) as exc_info:
        await _check_custom_key_allowed("sk-custom-key-123456")

    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_check_custom_key_allowed_none_key_always_passes(monkeypatch):
    """_check_custom_key_allowed does nothing when key is None, even if setting is on."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _check_custom_key_allowed,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {"disable_custom_api_keys": True})

    # Should not raise — None means auto-generate
    await _check_custom_key_allowed(None)


@pytest.mark.asyncio
async def test_get_new_token_rejected_when_custom_keys_disabled(monkeypatch):
    """get_new_token raises 403 when new_key is set and disable_custom_api_keys is true."""
    from fastapi import HTTPException

    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_new_token,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {"disable_custom_api_keys": True})

    data = RegenerateKeyRequest(new_key="sk-custom-regen-key")

    with pytest.raises(HTTPException) as exc_info:
        await get_new_token(data)

    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_get_new_token_auto_generates_when_custom_keys_disabled(monkeypatch):
    """get_new_token auto-generates a key when new_key is None, even if setting is on."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_new_token,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.general_settings", {"disable_custom_api_keys": True})

    data = RegenerateKeyRequest()  # no new_key
    result = await get_new_token(data)

    assert result.startswith("sk-")


@pytest.mark.asyncio
async def test_generate_service_account_requires_team_id():
    with pytest.raises(HTTPException):
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                metadata={"service_account_id": "sa"},
                team_id=None,
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"
            ),
            litellm_changed_by=None,
            team_table=None,
        )


@pytest.mark.asyncio
async def test_generate_service_account_works_with_team_id():
    from unittest.mock import patch

    # Mock the database and router dependencies from proxy_server
    with (
        patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma,
        patch("litellm.proxy.proxy_server.llm_router") as mock_router,
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):

        # Configure mocks
        mock_prisma.return_value = AsyncMock()
        mock_router.return_value = None
        # Mock the response from generate_key_helper_fn
        mock_generate_key.return_value = {
            "key": "sk-test-key",
            "expires": None,
            "user_id": "test-user",
            "team_id": "IJ",
        }

        # This should not raise an exception since team_id is provided
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                metadata={"service_account_id": "sa"},
                team_id="IJ",
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"
            ),
            litellm_changed_by=None,
            team_table=None,
        )


def _identity_json_object(value: dict[str, object]) -> dict[str, object]:
    return value


def _key_generation_prisma_client(
    project_record: dict[str, str] | None,
) -> tuple[MagicMock, MagicMock, MagicMock]:
    prisma_client: Final = MagicMock()
    prisma_client.jsonify_object.side_effect = _identity_json_object

    budget_table: Final = MagicMock()
    budget_table.create = AsyncMock(return_value=MagicMock(budget_id="created-budget-id"))
    budget_table.delete = AsyncMock()
    object_permission_table: Final = MagicMock()
    object_permission_table.create = AsyncMock(
        return_value=MagicMock(object_permission_id="created-object-permission-id")
    )
    object_permission_table.delete = AsyncMock()

    prisma_client.db.litellm_budgettable = budget_table
    prisma_client.db.litellm_objectpermissiontable = object_permission_table
    prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(return_value=project_record)
    prisma_client.insert_data = AsyncMock()
    return prisma_client, budget_table, object_permission_table


@pytest.mark.asyncio
async def test_rejected_key_generation_deletes_created_budget_and_default_permission(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    prisma_client, budget_table, object_permission_table = _key_generation_prisma_client(
        {"project_id": "project-b", "team_id": "team-b"}
    )
    monkeypatch.setattr(litellm, "key_generation_settings", None)
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"object_permission": {"vector_stores": ["default-vector-store"]}},
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)

    with pytest.raises(KeyProjectBindingError) as exc:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                budget_id="caller-budget-id",
                project_id="project-b",
                soft_budget=3.5,
                team_id="team-a",
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin",
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    assert exc.value.status_code == 400
    budget_table.create.assert_awaited_once()
    budget_table.delete.assert_awaited_once_with(where={"budget_id": "created-budget-id"})
    object_permission_table.create.assert_awaited_once_with(data={"vector_stores": ["default-vector-store"]})
    object_permission_table.delete.assert_awaited_once_with(
        where={"object_permission_id": "created-object-permission-id"}
    )
    prisma_client.insert_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_key_generation_does_not_delete_rows_for_other_http_exceptions(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    prisma_client, budget_table, object_permission_table = _key_generation_prisma_client(None)
    monkeypatch.setattr(litellm, "key_generation_settings", None)
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"object_permission": {"vector_stores": ["default-vector-store"]}},
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)

    with pytest.raises(HTTPException) as exc:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                project_id="project-b",
                router_settings={"weights": {"gpt-4": {"unknown-deployment": 1.0}}},
                soft_budget=3.5,
                team_id="team-a",
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin",
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    assert type(exc.value) is HTTPException
    assert exc.value.status_code == 400
    budget_table.create.assert_awaited_once()
    budget_table.delete.assert_not_awaited()
    object_permission_table.create.assert_awaited_once_with(data={"vector_stores": ["default-vector-store"]})
    object_permission_table.delete.assert_not_awaited()


@pytest.mark.asyncio
async def test_generate_key_throttle_rejected_for_non_admin():
    """Security regression: a non-admin creating a key must not be able to set
    throttle_on_budget_exceeded=true, which would let the new key keep spending
    past an admin-imposed per-key budget ceiling instead of hard-blocking. The
    /key/update gate does not cover generate, so generate needs its own admin
    check. Only the enable value is gated, so this must 403."""
    mock_prisma_client = AsyncMock()
    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        with pytest.raises(HTTPException) as exc:
            await _common_key_generation_helper(
                data=GenerateKeyRequest(throttle_on_budget_exceeded=True),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.INTERNAL_USER,
                    api_key="sk-alice",
                    user_id="alice",
                ),
                litellm_changed_by=None,
                team_table=None,
            )
    assert int(getattr(exc.value, "status_code", 0)) == 403
    assert "Only proxy admins can enable throttle_on_budget_exceeded" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_generate_key_throttle_allowed_for_admin():
    """A proxy admin may create a key with throttle_on_budget_exceeded=true; the
    generate admin gate must let the admin through to key creation."""
    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):
        mock_generate_key.return_value = {
            "key": "sk-test-key",
            "expires": None,
            "user_id": "admin",
            "team_id": None,
        }
        await _common_key_generation_helper(
            data=GenerateKeyRequest(throttle_on_budget_exceeded=True),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
            litellm_changed_by=None,
            team_table=None,
        )
    assert mock_generate_key.called


@pytest.mark.asyncio
async def test_generate_key_end_user_budget_id_rejected_for_non_admin():
    """A key's default end-user budget overrides the proxy-wide one, so a non-admin must not
    be able to pick a looser one for the customers their key creates."""
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_budgettable.find_unique = AsyncMock()
    with pytest.raises(HTTPException) as exc:
        await _validate_end_user_budget_id_change(
            requested_budget_id="svc-a-budget",
            existing_budget_id=None,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-alice",
                user_id="alice",
            ),
            prisma_client=mock_prisma_client,
        )
    assert int(getattr(exc.value, "status_code", 0)) == 403
    assert "Only proxy admins can set end_user_budget_id" in str(exc.value.detail)
    mock_prisma_client.db.litellm_budgettable.find_unique.assert_not_awaited()

    await _validate_end_user_budget_id_change(
        requested_budget_id="",
        existing_budget_id=None,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-alice",
            user_id="alice",
        ),
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_generate_key_end_user_budget_id_must_name_an_existing_budget():
    """A typo in end_user_budget_id would silently leave new customers on the proxy-wide default,
    so key creation rejects an id that matches no budget row."""
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=None)
    with pytest.raises(HTTPException) as exc:
        await _validate_end_user_budget_id_change(
            requested_budget_id="no-such-budget",
            existing_budget_id=None,
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
            prisma_client=mock_prisma_client,
        )
    assert int(getattr(exc.value, "status_code", 0)) == 400
    assert "no-such-budget" in str(exc.value.detail)
    mock_prisma_client.db.litellm_budgettable.find_unique.assert_awaited_once_with(
        where={"budget_id": "no-such-budget"}
    )


@pytest.mark.asyncio
async def test_generate_key_end_user_budget_id_lands_in_key_metadata():
    """The typed end_user_budget_id field is stored in key metadata, which is where auth reads it."""
    budget_row = MagicMock()
    budget_row.model_dump.return_value = {"budget_id": "svc-a-budget", "max_budget": 0.5}
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=budget_row)
    with (
        patch(  # test-quality-ok: the helper reads proxy_server globals, no seam
            "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
        ),
        patch("litellm.proxy.proxy_server.llm_router", None),  # test-quality-ok: read as a proxy_server global
        patch("litellm.proxy.proxy_server.premium_user", False),  # test-quality-ok: read as a proxy_server global
        patch(  # test-quality-ok: assertion is on the metadata handed to the db writer
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):
        mock_generate_key.return_value = {
            "key": "sk-test-key",
            "expires": None,
            "user_id": "admin",
            "team_id": None,
        }
        await _common_key_generation_helper(
            data=GenerateKeyRequest(end_user_budget_id="svc-a-budget"),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
            litellm_changed_by=None,
            team_table=None,
        )
    assert mock_generate_key.call_args.kwargs["metadata"] == {"end_user_budget_id": "svc-a-budget"}


@pytest.mark.asyncio
async def test_update_key_end_user_budget_id_folds_into_metadata_and_survives_omission():
    """/key/update with end_user_budget_id writes it into metadata; an update that omits the field
    (the edit form only sends what changed) keeps the value the key already had."""
    existing_key = LiteLLM_VerificationToken(token="hashed", metadata={"end_user_budget_id": "svc-a-budget"})

    updated = await prepare_key_update_data(
        data=UpdateKeyRequest(key="sk-1", end_user_budget_id="svc-b-budget"), existing_key_row=existing_key
    )
    assert updated["metadata"]["end_user_budget_id"] == "svc-b-budget"

    untouched = await prepare_key_update_data(
        data=UpdateKeyRequest(key="sk-1", key_alias="renamed"), existing_key_row=existing_key
    )
    assert untouched["metadata"]["end_user_budget_id"] == "svc-a-budget"


@pytest.mark.asyncio
async def test_update_key_clears_end_user_budget_id_with_empty_string():
    """Sending an empty end_user_budget_id detaches the key default without touching any budget row,
    so auth falls back to the proxy-wide default for that key's customers."""
    from litellm.proxy.auth.auth_checks import get_key_end_user_budget_id

    existing_key = LiteLLM_VerificationToken(token="hashed", metadata={"end_user_budget_id": "svc-a-budget"})
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=None)

    await _validate_update_key_data(
        data=UpdateKeyRequest(key="sk-1", end_user_budget_id=""),
        existing_key_row=existing_key,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
        llm_router=None,
        premium_user=False,
        prisma_client=mock_prisma_client,
        user_api_key_cache=MagicMock(),
    )
    cleared = await prepare_key_update_data(
        data=UpdateKeyRequest(key="sk-1", end_user_budget_id="", metadata={"end_user_budget_id": "svc-a-budget"}),
        existing_key_row=existing_key,
    )

    mock_prisma_client.db.litellm_budgettable.find_unique.assert_not_awaited()
    assert get_key_end_user_budget_id(cleared["metadata"]) is None


@pytest.mark.asyncio
async def test_update_key_metadata_body_without_end_user_budget_id_is_a_clear_for_non_admin():
    """/key/update replaces metadata wholesale, so a non-admin sending metadata that drops the field
    would detach the key default; that must be refused like an explicit clear, while an admin may do it."""
    existing_key = LiteLLM_VerificationToken(token="hashed", metadata={"end_user_budget_id": "svc-a-budget"})
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=None)
    non_admin = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-alice", user_id="alice")

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=UpdateKeyRequest(key="sk-1", metadata={"team": "ops"}),
            existing_key_row=existing_key,
            user_api_key_dict=non_admin,
            llm_router=None,
            premium_user=False,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert int(getattr(exc.value, "status_code", 0)) == 403

    await _validate_end_user_budget_id_change(
        requested_budget_id=_requested_end_user_budget_id(
            UpdateKeyRequest(key="sk-1", metadata={"team": "ops", "end_user_budget_id": "svc-a-budget"})
        ),
        existing_budget_id="svc-a-budget",
        user_api_key_dict=non_admin,
        prisma_client=mock_prisma_client,
    )
    await _validate_end_user_budget_id_change(
        requested_budget_id=_requested_end_user_budget_id(UpdateKeyRequest(key="sk-1", metadata={"team": "ops"})),
        existing_budget_id="svc-a-budget",
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
        prisma_client=mock_prisma_client,
    )
    assert _requested_end_user_budget_id(UpdateKeyRequest(key="sk-1", key_alias="renamed")) is None
    mock_prisma_client.db.litellm_budgettable.find_unique.assert_not_awaited()


@pytest.mark.asyncio
async def test_regenerate_key_end_user_budget_id_rejected_for_non_admin():
    """/key/regenerate also accepts key params, so a non-admin must not be able to use it to attach
    a looser default customer budget that /key/generate and /key/update would refuse."""
    from litellm.proxy._types import RegenerateKeyRequest

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock()
    with pytest.raises(HTTPException) as exc:
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=LiteLLM_VerificationToken(token="hashed", user_id="alice"),
            hashed_api_key="hashed",
            key="hashed",
            data=RegenerateKeyRequest(end_user_budget_id="svc-a-budget"),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-alice", user_id="alice"
            ),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )
    assert int(getattr(exc.value, "status_code", 0)) == 403
    assert "Only proxy admins can set end_user_budget_id" in str(exc.value.detail)
    mock_prisma_client.db.litellm_verificationtoken.update.assert_not_awaited()


@pytest.mark.asyncio
async def test_update_service_account_requires_team_id():
    data = UpdateKeyRequest(key="sk-1", metadata={"service_account_id": "sa"})
    existing_key = LiteLLM_VerificationToken(token="hashed", team_id=None)

    with pytest.raises(HTTPException):
        await prepare_key_update_data(data=data, existing_key_row=existing_key)


@pytest.mark.asyncio
async def test_update_service_account_works_with_team_id():
    data = UpdateKeyRequest(
        key="sk-1", metadata={"service_account_id": "sa"}, team_id="IJ"
    )
    existing_key = LiteLLM_VerificationToken(token="hashed")

    await prepare_key_update_data(data=data, existing_key_row=existing_key)


@pytest.mark.asyncio
@pytest.mark.parametrize("flag_value", [True, False])
async def test_update_key_enable_prompt_caching_folds_into_metadata(flag_value):
    """Top-level enable_prompt_caching on /key/update lands in key metadata, including flipping back to False."""
    data = UpdateKeyRequest(key="sk-1", enable_prompt_caching=flag_value)
    existing_key = LiteLLM_VerificationToken(
        token="hashed", metadata={"enable_prompt_caching": not flag_value}
    )

    updated = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert updated["metadata"]["enable_prompt_caching"] is flag_value
    assert "enable_prompt_caching" not in {k for k in updated if k != "metadata"}


@pytest.mark.asyncio
@pytest.mark.parametrize("tpd_limit", [250000, None])
async def test_update_key_writes_tpd_limit_as_a_column(tpd_limit):
    data = UpdateKeyRequest(key="sk-1", tpd_limit=tpd_limit)
    existing_key = LiteLLM_VerificationToken(token="hashed", tpd_limit=1)

    updated = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert updated["tpd_limit"] == tpd_limit
    assert "rpm_limit" not in updated


@pytest.mark.asyncio
async def test_update_preserves_service_account_id_when_metadata_replaced():
    """
    Regression: /key/update wholesale-replaced metadata, silently dropping
    service_account_id. The pre-call check then treated the key as a regular
    key and bypassed service_account_settings.enforced_params.
    """
    data = UpdateKeyRequest(
        key="sk-1",
        metadata={"unrelated": "value"},
        team_id="IJ",
    )
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-123"},
    )

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert result["metadata"]["service_account_id"] == "sa-123"
    assert result["metadata"]["unrelated"] == "value"


@pytest.mark.asyncio
async def test_update_rejects_service_account_id_overwrite():
    """
    Once assigned, a key's service_account_id is an identity marker — rebinding
    it via update would break spend attribution. Reject rather than silently
    ignore so scripted callers surface the bug.
    """
    data = UpdateKeyRequest(
        key="sk-1",
        metadata={"service_account_id": "sa-new"},
        team_id="IJ",
    )
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-old"},
    )

    with pytest.raises(HTTPException) as exc_info:
        await prepare_key_update_data(data=data, existing_key_row=existing_key)
    assert exc_info.value.status_code == 400


@pytest.mark.asyncio
async def test_update_allows_matching_service_account_id():
    """Resending the same value (e.g. UI round-trip) is a no-op, not a conflict."""
    data = UpdateKeyRequest(
        key="sk-1",
        metadata={"service_account_id": "sa-123", "other": "value"},
        team_id="IJ",
    )
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-123"},
    )

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert result["metadata"]["service_account_id"] == "sa-123"
    assert result["metadata"]["other"] == "value"


@pytest.mark.asyncio
async def test_update_rejects_explicit_null_service_account_id():
    """
    Explicit null is an attempt to clear — not an omission. Silently ignoring
    it would let a caller think they cleared the field when they didn't, so
    treat it the same as any other rebind attempt and return 400.
    """
    data = UpdateKeyRequest(
        key="sk-1",
        metadata={"service_account_id": None},
        team_id="IJ",
    )
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-old"},
    )

    with pytest.raises(HTTPException) as exc_info:
        await prepare_key_update_data(data=data, existing_key_row=existing_key)
    assert exc_info.value.status_code == 400


@pytest.mark.asyncio
async def test_update_rejects_whole_metadata_null_on_service_account_key():
    """
    `metadata: null` on a key with a reserved field would have dereferenced None
    inside the reserved-field loop and returned a 500. Must surface as a 400
    since the effect would be to clear an immutable field.
    """
    data = UpdateKeyRequest(key="sk-1", metadata=None, team_id="IJ")
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-123"},
    )

    with pytest.raises(HTTPException) as exc_info:
        await prepare_key_update_data(data=data, existing_key_row=existing_key)
    assert exc_info.value.status_code == 400


@pytest.mark.asyncio
async def test_update_without_metadata_still_preserves_existing():
    """Omitting metadata entirely must not drop existing metadata fields."""
    data = UpdateKeyRequest(key="sk-1", max_budget=100)
    existing_key = LiteLLM_VerificationToken(
        token="hashed",
        team_id="IJ",
        metadata={"service_account_id": "sa-123", "other": "kept"},
    )

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert result["metadata"]["service_account_id"] == "sa-123"
    assert result["metadata"]["other"] == "kept"


@pytest.mark.asyncio
async def test_prepare_key_update_data_encrypts_callback_vars(monkeypatch):
    """/key/update must encrypt callback_vars values before they reach the DB."""
    from litellm.proxy.common_utils.callback_utils import decrypt_callback_vars

    monkeypatch.setenv("LITELLM_SALT_KEY", "test-salt-32-bytes-aaaaaaaaaaaaaa")
    data = UpdateKeyRequest(
        key="sk-1",
        metadata={
            "logging": [
                {
                    "callback_name": "langfuse",
                    "callback_type": "success",
                    "callback_vars": {
                        "langfuse_public_key": "pk-real",
                        "langfuse_secret_key": "sk-real",
                    },
                }
            ]
        },
    )
    existing_key = LiteLLM_VerificationToken(token="hashed")

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    cv = result["metadata"]["logging"][0]["callback_vars"]
    assert cv["langfuse_secret_key"] != "sk-real"
    assert cv["langfuse_public_key"] != "pk-real"
    recovered = decrypt_callback_vars(result["metadata"])["logging"][0]["callback_vars"]
    assert recovered["langfuse_secret_key"] == "sk-real"
    assert recovered["langfuse_public_key"] == "pk-real"


@pytest.mark.asyncio
async def test_prepare_key_update_data_duration_never_expires():
    """Test that duration="-1" sets expires to None (never expires)."""
    from litellm.proxy._types import UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    # Mock existing key
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        auto_rotate=False,
        rotation_interval=None,
        metadata={},
    )

    # Test setting duration to "-1" (never expires)
    update_request = UpdateKeyRequest(key="test-token", duration="-1")

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    # Verify that expires is set to None
    assert result["expires"] is None


@pytest.mark.asyncio
async def test_prepare_key_update_data_duration_none_never_expires():
    """Test that duration=None sets expires to None (never expires)."""
    from litellm.proxy._types import UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        auto_rotate=False,
        rotation_interval=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(key="test-token", duration=None)

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    assert result["expires"] is None


@pytest.mark.asyncio
@pytest.mark.parametrize("cleared_value", [[], None])
async def test_prepare_key_update_data_budget_limits_clears_field(cleared_value):
    """budget_limits=[] / None must serialize to JSON null, never reach Prisma raw."""
    from litellm.proxy._types import UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(key="test-token", budget_limits=cleared_value)

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    assert result["budget_limits"] == json.dumps(None)


@pytest.mark.asyncio
async def test_prepare_key_update_data_budget_limits_serializes_windows():
    """Non-empty budget_limits stay JSON-encoded with reset_at initialized."""
    from litellm.proxy._types import UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(
        key="test-token",
        budget_limits=[{"budget_duration": "1d", "max_budget": 10.0}],
    )

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    windows = json.loads(result["budget_limits"])
    assert isinstance(result["budget_limits"], str)
    assert windows[0]["max_budget"] == 10.0
    assert windows[0]["reset_at"] is not None


def _key_with_weekly_window(reset_at: datetime) -> LiteLLM_VerificationToken:
    return LiteLLM_VerificationToken(
        token="test-token",
        user_id="test-user",
        metadata={},
        budget_limits=[{"budget_duration": "7d", "max_budget": 50.0, "reset_at": reset_at.isoformat()}],
    )


async def _updated_windows_by_duration(
    existing_key: LiteLLM_VerificationToken, budget_limits: list[dict[str, object]]
) -> dict[str, dict[str, object]]:
    result: Final = await prepare_key_update_data(
        data=UpdateKeyRequest.model_validate({"key": "test-token", "budget_limits": budget_limits}),
        existing_key_row=existing_key,
    )
    return {window["budget_duration"]: window for window in json.loads(result["budget_limits"])}


@pytest.mark.asyncio
@pytest.mark.parametrize("weekly_cap", [50.0, 40.0, 60.0])
async def test_prepare_key_update_data_keeps_a_resubmitted_window_mid_period(weekly_cap: float) -> None:
    open_reset_at: Final = datetime.now(timezone.utc) + timedelta(days=3)

    windows: Final = await _updated_windows_by_duration(
        _key_with_weekly_window(open_reset_at),
        [{"budget_duration": "7d", "max_budget": weekly_cap}, {"budget_duration": "1d", "max_budget": 5.0}],
    )

    assert datetime.fromisoformat(windows["7d"]["reset_at"]) == open_reset_at
    assert windows["7d"]["max_budget"] == weekly_cap
    assert datetime.fromisoformat(windows["1d"]["reset_at"]) > datetime.now(timezone.utc)


@pytest.mark.asyncio
async def test_prepare_key_update_data_restarts_a_resubmitted_window_whose_period_ended() -> None:
    stale_reset_at: Final = datetime.now(timezone.utc) - timedelta(days=1)

    windows: Final = await _updated_windows_by_duration(
        _key_with_weekly_window(stale_reset_at), [{"budget_duration": "7d", "max_budget": 50.0}]
    )

    assert datetime.fromisoformat(windows["7d"]["reset_at"]) > datetime.now(timezone.utc)


@pytest.mark.asyncio
async def test_prepare_key_update_data_disable_global_guardrails_false_no_premium(
    monkeypatch,
):
    """
    Regression #30285: editing a key via the UI sends disable_global_guardrails=False
    (unchanged default). A non-premium user must NOT get a 403, and False must persist.
    """
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)
    data = UpdateKeyRequest(key="sk-1", disable_global_guardrails=False)
    existing_key = LiteLLM_VerificationToken(token="hashed")

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert result["metadata"]["disable_global_guardrails"] is False


@pytest.mark.asyncio
async def test_prepare_key_update_data_disable_global_guardrails_true_requires_premium(
    monkeypatch,
):
    """Control: enabling the premium feature (True) without a license still 403s."""
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)
    data = UpdateKeyRequest(key="sk-1", disable_global_guardrails=True)
    existing_key = LiteLLM_VerificationToken(token="hashed")

    with pytest.raises(HTTPException) as exc_info:
        await prepare_key_update_data(data=data, existing_key_row=existing_key)
    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_prepare_key_update_data_disable_global_guardrails_true_premium_persists(
    monkeypatch,
):
    """A premium user enabling the feature (True) succeeds and the value persists."""
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    data = UpdateKeyRequest(key="sk-1", disable_global_guardrails=True)
    existing_key = LiteLLM_VerificationToken(token="hashed")

    result = await prepare_key_update_data(data=data, existing_key_row=existing_key)

    assert result["metadata"]["disable_global_guardrails"] is True


@pytest.mark.asyncio
async def test_validate_team_id_used_in_service_account_request_requires_team_id():
    """
    Test that validate_team_id_used_in_service_account_request raises HTTPException
    when team_id is None for service account key generation.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        validate_team_id_used_in_service_account_request,
    )

    mock_prisma_client = AsyncMock()

    # Test that HTTPException is raised when team_id is None
    with pytest.raises(HTTPException) as exc_info:
        await validate_team_id_used_in_service_account_request(
            team_id=None,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert "team_id is required for service account keys" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_validate_team_id_used_in_service_account_request_requires_prisma_client():
    """
    Test that validate_team_id_used_in_service_account_request raises HTTPException
    when prisma_client is None for service account key generation.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        validate_team_id_used_in_service_account_request,
    )

    # Test that HTTPException is raised when prisma_client is None
    with pytest.raises(HTTPException) as exc_info:
        await validate_team_id_used_in_service_account_request(
            team_id="test-team-id",
            prisma_client=None,
        )

    assert exc_info.value.status_code == 400
    assert "prisma_client is required for service account keys" in str(
        exc_info.value.detail
    )


@pytest.mark.asyncio
async def test_validate_team_id_used_in_service_account_request_checks_team_exists():
    """
    Test that validate_team_id_used_in_service_account_request validates that
    the team_id exists in the database for service account key generation.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        validate_team_id_used_in_service_account_request,
    )

    mock_prisma_client = AsyncMock()

    # Mock the database query to return None (team doesn't exist)
    mock_find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_teamtable.find_unique = mock_find_unique

    # Test that HTTPException is raised when team doesn't exist in DB
    with pytest.raises(HTTPException) as exc_info:
        await validate_team_id_used_in_service_account_request(
            team_id="non-existent-team-id",
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert "team_id does not exist in the database" in str(exc_info.value.detail)

    # Verify the database was queried with the correct parameters
    mock_find_unique.assert_called_once_with(where={"team_id": "non-existent-team-id"})


@pytest.mark.asyncio
async def test_validate_team_id_used_in_service_account_request_success():
    """
    Test that validate_team_id_used_in_service_account_request returns True
    when team_id exists in the database for service account key generation.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        validate_team_id_used_in_service_account_request,
    )

    mock_prisma_client = AsyncMock()

    # Mock the database query to return a team object (team exists)
    mock_team = {"team_id": "existing-team-id", "team_name": "Test Team"}
    mock_find_unique = AsyncMock(return_value=mock_team)
    mock_prisma_client.db.litellm_teamtable.find_unique = mock_find_unique

    # Test that function returns True when team exists
    result = await validate_team_id_used_in_service_account_request(
        team_id="existing-team-id",
        prisma_client=mock_prisma_client,
    )

    assert result is True

    # Verify the database was queried with the correct parameters
    mock_find_unique.assert_called_once_with(where={"team_id": "existing-team-id"})


@pytest.mark.asyncio
async def test_generate_service_account_key_endpoint_validation():
    """
    Test that the /key/service-account/generate endpoint properly validates
    team_id requirement and team existence in database.
    """
    from unittest.mock import patch

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_service_account_key_fn,
    )

    # Test case 1: Missing team_id
    with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
        # Mock prisma_client to be not None so we can reach team_id validation
        mock_prisma_instance = AsyncMock()
        mock_prisma.return_value = mock_prisma_instance

        with pytest.raises(HTTPException) as exc_info:
            await generate_service_account_key_fn(
                data=GenerateKeyRequest(team_id=None),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"
                ),
                litellm_changed_by=None,
            )

        assert exc_info.value.status_code == 400
        assert "team_id is required for service account keys" in str(
            exc_info.value.detail
        )

    # Test case 2: Team doesn't exist in database
    with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:
        # Mock team not found
        mock_find_unique = AsyncMock(return_value=None)
        mock_prisma.db.litellm_teamtable.find_unique = mock_find_unique

        with pytest.raises(HTTPException) as exc_info:
            await generate_service_account_key_fn(
                data=GenerateKeyRequest(team_id="non-existent-team"),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"
                ),
                litellm_changed_by=None,
            )

        assert exc_info.value.status_code == 400
        assert "team_id does not exist in the database" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_unblock_key_supports_both_sk_and_hashed_tokens(monkeypatch):
    """
    Test that the unblock_key endpoint correctly handles both sk- prefixed tokens
    and hashed tokens by properly converting sk- tokens to hashed format before
    database operations.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import unblock_key

    # Mock dependencies
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    # Use a proper 64-character hex hash for testing
    test_hashed_token = (
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    )

    # Mock the key record that will be returned from database
    mock_key_record = MagicMock()
    mock_key_record.token = test_hashed_token
    mock_key_record.blocked = False
    mock_key_record.model_dump_json.return_value = (
        f'{{"token": "{test_hashed_token}", "blocked": false}}'
    )

    # Mock database operations
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_record
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=mock_key_record
    )

    # Mock hash_token function
    def mock_hash_token(token):
        if token == "sk-test123456789":
            return test_hashed_token
        return token

    # Apply monkeypatch
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
    monkeypatch.setattr(
        "litellm.store_audit_logs", False
    )  # Disable audit logs for simpler test

    # Mock get_key_object and _cache_key_object
    async def mock_delete_cache_key_object(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        mock_delete_cache_key_object,
    )

    # Create mock request and user auth
    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    # Test Case 1: Using sk- prefixed token
    sk_token_request = BlockKeyRequest(key="sk-test123456789")

    result = await unblock_key(
        data=sk_token_request,
        http_request=mock_request,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )

    # Verify that the database update was called with hashed token
    sk_token_call = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs
    assert sk_token_call["where"] == {"token": test_hashed_token}
    assert sk_token_call["data"]["blocked"] is False

    assert result == mock_key_record

    # Reset mocks for second test
    mock_prisma_client.db.litellm_verificationtoken.update.reset_mock()

    # Test Case 2: Using already hashed token
    hashed_token_request = BlockKeyRequest(key=test_hashed_token)

    result = await unblock_key(
        data=hashed_token_request,
        http_request=mock_request,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )

    # Verify that the database update was called with the same hashed token
    hashed_token_call = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs
    assert hashed_token_call["where"] == {"token": test_hashed_token}
    assert hashed_token_call["data"]["blocked"] is False

    assert result == mock_key_record


@pytest.mark.asyncio
async def test_unblock_key_invalid_key_format(monkeypatch):
    """
    Test that unblock_key properly validates key format and raises appropriate errors
    for invalid keys.
    """
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import unblock_key
    from litellm.proxy.utils import ProxyException

    # Mock prisma_client to avoid DB connection error
    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Mock request and user auth
    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    # Test with invalid key format
    invalid_key_request = BlockKeyRequest(key="invalid-key-format")

    with pytest.raises(ProxyException) as exc_info:
        await unblock_key(
            data=invalid_key_request,
            http_request=mock_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc_info.value.code == "400"
    assert "Invalid key format" in str(exc_info.value.message)


@pytest.mark.asyncio
async def test_block_key_nonexistent_key_returns_404(monkeypatch):
    """
    Test that block_key returns 404 (not misleading 401) when the key
    doesn't exist in the database, even when the caller is authenticated
    as a proxy admin.

    Previously, block_key would call get_key_object() for cache refresh,
    which raised a 401 ProxyException with 'Authentication Error' — making
    it look like an auth failure when it was really a missing-key error.
    """
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    # find_unique returns None → key does not exist
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    def mock_hash_token(token):
        return "abcd1234" * 8  # 64-char hex

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    data = BlockKeyRequest(key="sk-does-not-exist-key")

    with pytest.raises(ProxyException) as exc_info:
        await block_key(
            data=data,
            http_request=mock_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc_info.value.code == "404"
    assert "not found" in str(exc_info.value.message).lower()
    # Must NOT contain "Authentication Error"
    assert "Authentication Error" not in str(exc_info.value.message)
    # update should never be called since the key doesn't exist
    mock_prisma_client.db.litellm_verificationtoken.update.assert_not_called()


@pytest.mark.asyncio
async def test_unblock_key_nonexistent_key_returns_404(monkeypatch):
    """
    Test that unblock_key returns 404 (not misleading 401) when the key
    doesn't exist in the database.
    """
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        unblock_key,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    # find_unique returns None → key does not exist
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    def mock_hash_token(token):
        return "abcd1234" * 8

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    data = BlockKeyRequest(key="sk-does-not-exist-key")

    with pytest.raises(ProxyException) as exc_info:
        await unblock_key(
            data=data,
            http_request=mock_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc_info.value.code == "404"
    assert "not found" in str(exc_info.value.message).lower()
    assert "Authentication Error" not in str(exc_info.value.message)
    mock_prisma_client.db.litellm_verificationtoken.update.assert_not_called()


@pytest.mark.asyncio
async def test_update_key_nonexistent_key_returns_404(monkeypatch):
    """
    Test that update_key_fn returns 404 (not misleading 401) when the body
    key doesn't exist in the database, even when the caller is authenticated
    as a proxy admin via the Authorization header.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    # find_unique returns None → key does not exist
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    data = UpdateKeyRequest(key="sk-does-not-exist-key")

    with pytest.raises(ProxyException) as exc_info:
        await update_key_fn(
            request=mock_request,
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc_info.value.code == "404"
    assert "not found" in str(exc_info.value.message).lower()
    assert "Authentication Error" not in str(exc_info.value.message)


def _setup_update_key_mocks(monkeypatch, mock_prisma_client):
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    proxy_logging_obj: Final = MagicMock()
    proxy_logging_obj.service_logging_obj.async_service_success_hook = AsyncMock()
    proxy_logging_obj.service_logging_obj.async_service_failure_hook = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", proxy_logging_obj)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)


@pytest.mark.asyncio
@pytest.mark.parametrize("bad_duration", ["0s", "-5m"])
async def test_update_key_rejects_a_duration_that_never_advances(monkeypatch, bad_duration):
    """A zero-length window resets to "now", so the key row is due again the
    moment it is written. The reset job re-reads such rows on every tick, and a
    tenant with enough of them fills each batch and starves other tenants.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    hashed_token = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
    key_in_db = LiteLLM_VerificationToken(token=hashed_token, user_id="test-user")

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.update_data = AsyncMock()
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with pytest.raises(ProxyException) as exc_info:
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key=hashed_token, budget_duration=bad_duration),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
            ),
            litellm_changed_by=None,
        )

    assert str(exc_info.value.code) == "400"
    assert "Invalid budget_duration" in str(exc_info.value.message)
    mock_prisma_client.update_data.assert_not_awaited()


@pytest.mark.asyncio
@pytest.mark.parametrize("bad_duration", ["0s", "-5m"])
async def test_generate_key_rejects_a_duration_that_never_advances(monkeypatch, bad_duration):
    """/key/generate must reject the same never-advancing durations /key/update does."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new=AsyncMock(),
    ) as mock_generate:
        with pytest.raises(ProxyException) as exc_info:
            await generate_key_fn(
                data=GenerateKeyRequest(budget_duration=bad_duration),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876", user_id="1234"
                ),
            )

    assert str(exc_info.value.code) == "400"
    assert "Invalid budget_duration" in str(exc_info.value.message)
    mock_generate.assert_not_awaited()


@pytest.mark.asyncio
async def test_update_key_by_alias_only(monkeypatch):
    """
    /key/update identified by key_alias alone resolves the key row via
    find_many on the alias and updates using the resolved token.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    hashed_token = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_token,
        key_alias="prod-alias",
        user_id="test-user",
        max_budget=200.0,
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[key_in_db]
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(
        return_value={"data": {"max_budget": 50.0}}
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
    )

    request_data = UpdateKeyRequest(key_alias="prod-alias", max_budget=50.0)

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
    ) as mock_delete_cache:
        mock_delete_cache.return_value = None
        result = await update_key_fn(
            request=MagicMock(),
            data=request_data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    mock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(
        where={"key_alias": "prod-alias"}, take=2
    )
    assert request_data.key == hashed_token
    mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_not_called()
    mock_prisma_client.update_data.assert_awaited_once()
    assert mock_prisma_client.update_data.call_args.kwargs["token"] == hashed_token
    assert (
        mock_prisma_client.update_data.call_args.kwargs["data"]["token"] == hashed_token
    )
    assert result["key"] == hashed_token


@pytest.mark.asyncio
async def test_update_key_changed_alias_must_match_key_alias_pattern(monkeypatch: pytest.MonkeyPatch) -> None:
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    monkeypatch.setattr(litellm, "key_alias_pattern", r"^[a-z0-9]+(-[a-z0-9]+)*$")
    hashed_token = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
    key_in_db = LiteLLM_VerificationToken(token=hashed_token, key_alias="Legacy Alias", user_id="test-user")

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=key_in_db)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[key_in_db])
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(return_value=None)
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {"max_budget": 50.0}})
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
    )

    with pytest.raises(ProxyException) as exc_info:
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key=hashed_token, key_alias="Prod Key"),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
    assert str(exc_info.value.code) == "400"
    assert "key_alias_pattern" in str(exc_info.value.message)
    mock_prisma_client.update_data.assert_not_awaited()

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        return_value=None,
    ):
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key=hashed_token, key_alias="Legacy Alias", max_budget=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
    mock_prisma_client.update_data.assert_awaited_once()


@pytest.mark.asyncio
async def test_update_key_by_alias_not_found_returns_404(monkeypatch):
    """
    /key/update with a key_alias matching no key returns 404.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
    )

    with pytest.raises(ProxyException) as exc_info:
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key_alias="no-such-alias", max_budget=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert str(exc_info.value.code) == "404"
    assert "not found" in str(exc_info.value.message).lower()
    mock_prisma_client.update_data.assert_not_called()


@pytest.mark.asyncio
async def test_update_key_by_duplicate_alias_returns_400(monkeypatch):
    """
    /key/update with a key_alias shared by multiple keys returns 400
    instead of silently updating one of them.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    rows = [
        LiteLLM_VerificationToken(token="hashed-token-1", key_alias="dup-alias"),
        LiteLLM_VerificationToken(token="hashed-token-2", key_alias="dup-alias"),
    ]
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=rows
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
    )

    with pytest.raises(ProxyException) as exc_info:
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key_alias="dup-alias", max_budget=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert str(exc_info.value.code) == "400"
    assert "multiple keys" in str(exc_info.value.message).lower()
    mock_prisma_client.update_data.assert_not_called()


@pytest.mark.asyncio
async def test_update_key_with_key_and_alias_selects_by_key(monkeypatch):
    """
    Regression: passing both key and key_alias keeps today's behavior. The key
    identifies the row (find_unique, never find_many) and key_alias is the new
    alias to set; the response echoes the caller-passed key.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    hashed_token = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_token,
        key_alias="old-name",
        user_id="test-user",
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(
        return_value={"data": {"key_alias": "new-name"}}
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
    ) as mock_delete_cache:
        mock_delete_cache.return_value = None
        result = await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key="sk-test-key", key_alias="new-name"),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    mock_prisma_client.db.litellm_verificationtoken.find_many.assert_not_called()
    mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once()
    assert mock_prisma_client.update_data.call_args.kwargs["token"] == "sk-test-key"
    assert result["key"] == "sk-test-key"


@pytest.mark.asyncio
async def test_block_key_existing_key_succeeds(monkeypatch):
    """
    Test that block_key successfully blocks an existing key and
    invalidates the cache entry.
    """
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = (
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    )

    mock_key_record = MagicMock()
    mock_key_record.token = test_hashed_token
    mock_key_record.blocked = False
    mock_key_record.model_dump_json.return_value = (
        f'{{"token": "{test_hashed_token}", "blocked": false}}'
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_record
    )
    mock_updated_record = MagicMock()
    mock_updated_record.token = test_hashed_token
    mock_updated_record.blocked = True
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=mock_updated_record
    )

    def mock_hash_token(token):
        if token.startswith("sk-"):
            return test_hashed_token
        return token

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    # Mock _delete_cache_key_object
    async def mock_delete_cache_key_object(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        mock_delete_cache_key_object,
    )

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
    )

    data = BlockKeyRequest(key="sk-test123456789")

    result = await block_key(
        data=data,
        http_request=mock_request,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )

    # Verify the key was found and updated
    mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once_with(
        where={"token": test_hashed_token}
    )
    mock_prisma_client.db.litellm_verificationtoken.update.assert_called_once()
    block_call = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs
    assert block_call["where"] == {"token": test_hashed_token}
    assert block_call["data"]["blocked"] is True
    assert result == mock_updated_record


@pytest.mark.asyncio
@pytest.mark.parametrize("endpoint_name", ["block_key", "unblock_key"])
async def test_block_and_unblock_write_no_audit_row_when_the_key_update_fails(monkeypatch, endpoint_name):
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints import key_management_endpoints
    from litellm.proxy.management_helpers.audit_logs import drain_audit_tasks

    hashed_token = "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    existing_key_record = MagicMock()
    existing_key_record.token = hashed_token
    existing_key_record.model_dump_json.return_value = f'{{"token": "{hashed_token}"}}'

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing_key_record)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(side_effect=RuntimeError("update failed"))
    audit_writer = AsyncMock()

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.create_audit_log_for_update", audit_writer)
    monkeypatch.setattr("litellm.store_audit_logs", True)

    with pytest.raises(RuntimeError, match="update failed"):
        await getattr(key_management_endpoints, endpoint_name)(
            data=BlockKeyRequest(key=hashed_token),
            http_request=MagicMock(),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin_user"
            ),
            litellm_changed_by=None,
        )
    await drain_audit_tasks(timeout=1.0)

    assert audit_writer.call_count == 0


@pytest.mark.asyncio
async def test_validate_key_team_change_with_member_permissions():
    """
    Test validate_key_team_change function with team member permissions.

    This test covers the new logic that allows team members with specific
    permissions to update keys, not just team admins.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    from litellm.proxy._types import KeyManagementRoutes

    # Create mock objects
    mock_key = MagicMock()
    mock_key.user_id = "test-user-123"
    mock_key.models = ["gpt-4"]
    mock_key.tpm_limit = None
    mock_key.rpm_limit = None

    mock_team = MagicMock()
    mock_team.team_id = "test-team-456"
    mock_team.members_with_roles = []
    mock_team.tpm_limit = None
    mock_team.rpm_limit = None

    mock_change_initiator = MagicMock()
    mock_change_initiator.user_id = "test-user-123"

    mock_router = MagicMock()

    # Mock the member object returned by _get_user_in_team
    mock_member_object = MagicMock()

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.can_team_access_model",
        new_callable=AsyncMock,
    ):
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._get_user_in_team"
        ) as mock_get_user:
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.does_team_member_have_permissions_for_endpoint"
            ) as mock_has_perms:
                mock_get_user.return_value = mock_member_object
                mock_has_perms.return_value = True

                # This should not raise an exception due to member permissions
                await validate_key_team_change(
                    key=mock_key,
                    team=mock_team,
                    change_initiated_by=mock_change_initiator,
                    llm_router=mock_router,
                )

                # Verify the permission check was called with correct parameters
                mock_has_perms.assert_called_once_with(
                    team_member_role=mock_member_object.role,
                    team_table=mock_team,
                    route=KeyManagementRoutes.KEY_UPDATE.value,
                )


@pytest.mark.asyncio
async def test_validate_key_team_change_skips_all_team_models_sentinel():
    """
    Test that validate_key_team_change skips the 'all-team-models' sentinel
    value when checking if the target team can access the key's models.

    Keys with models=["all-team-models"] mean "use whatever models the team
    allows", so moving them to any team should not fail model validation.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    mock_key = MagicMock()
    mock_key.user_id = "test-user-123"
    mock_key.models = ["all-team-models"]
    mock_key.tpm_limit = None
    mock_key.rpm_limit = None

    mock_team = MagicMock()
    mock_team.team_id = "test-team-456"
    mock_team.models = ["gpt-4", "claude-3"]
    mock_team.members_with_roles = []
    mock_team.tpm_limit = None
    mock_team.rpm_limit = None

    mock_change_initiator = MagicMock()
    mock_change_initiator.user_id = "test-user-123"
    mock_change_initiator.user_role = LitellmUserRoles.PROXY_ADMIN.value

    mock_router = MagicMock()

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.can_team_access_model",
        new_callable=AsyncMock,
    ) as mock_can_access:
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._get_user_in_team"
        ) as mock_get_user:
            mock_get_user.return_value = MagicMock()

            await validate_key_team_change(
                key=mock_key,
                team=mock_team,
                change_initiated_by=mock_change_initiator,
                llm_router=mock_router,
            )

            # can_team_access_model should NOT have been called since
            # "all-team-models" is a sentinel that should be skipped
            mock_can_access.assert_not_called()


def test_key_rotation_fields_helper():
    """
    Test the key data update logic for rotation fields.

    This test focuses on the core logic that adds rotation fields to key_data
    when auto_rotate is enabled, without the complexity of full key generation.
    """
    # Test Case 1: With rotation enabled
    key_data = {"models": ["gpt-3.5-turbo"], "user_id": "test-user"}

    auto_rotate = True
    rotation_interval = "30d"

    # Simulate the rotation logic from generate_key_helper_fn
    if auto_rotate and rotation_interval:
        key_data.update(
            {"auto_rotate": auto_rotate, "rotation_interval": rotation_interval}
        )

    # Verify rotation fields are added
    assert key_data["auto_rotate"] == True
    assert key_data["rotation_interval"] == "30d"
    assert key_data["models"] == ["gpt-3.5-turbo"]  # Original fields preserved

    # Test Case 2: Without rotation enabled
    key_data2 = {"models": ["gpt-4"], "user_id": "test-user"}

    auto_rotate2 = False
    rotation_interval2 = None

    # Simulate the rotation logic
    if auto_rotate2 and rotation_interval2:
        key_data2.update(
            {"auto_rotate": auto_rotate2, "rotation_interval": rotation_interval2}
        )

    # Verify rotation fields are NOT added
    assert "auto_rotate" not in key_data2
    assert "rotation_interval" not in key_data2
    assert key_data2["models"] == ["gpt-4"]  # Original fields preserved

    # Test Case 3: auto_rotate=True but no interval
    key_data3 = {"models": ["claude-3"], "user_id": "test-user"}

    auto_rotate3 = True
    rotation_interval3 = None

    # Simulate the rotation logic
    if auto_rotate3 and rotation_interval3:
        key_data3.update(
            {"auto_rotate": auto_rotate3, "rotation_interval": rotation_interval3}
        )

    # Verify rotation fields are NOT added (missing interval)
    assert "auto_rotate" not in key_data3
    assert "rotation_interval" not in key_data3


@pytest.mark.asyncio
async def test_update_key_fn_auto_rotate_enable():
    """Test that update_key_fn properly handles enabling auto rotation."""
    from litellm.proxy._types import LiteLLM_VerificationToken, UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    # Mock existing key
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        auto_rotate=False,
        rotation_interval=None,
        metadata={},
    )

    # Test enabling auto rotation
    update_request = UpdateKeyRequest(
        key="test-token", auto_rotate=True, rotation_interval="30d"
    )

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    # Verify rotation fields are included
    assert result["auto_rotate"] is True
    assert result["rotation_interval"] == "30d"


@pytest.mark.asyncio
async def test_update_key_fn_auto_rotate_disable():
    """Test that update_key_fn properly handles disabling auto rotation."""
    from litellm.proxy._types import LiteLLM_VerificationToken, UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    # Mock existing key with rotation enabled
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        auto_rotate=True,
        rotation_interval="30d",
        metadata={},
    )

    # Test disabling auto rotation
    update_request = UpdateKeyRequest(key="test-token", auto_rotate=False)

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    # Verify auto_rotate is set to False
    assert result["auto_rotate"] is False


@pytest.mark.asyncio
async def test_check_team_key_limits_no_existing_keys():
    """
    Test _check_team_key_limits when team has no existing keys.
    Should allow any TPM/RPM limits within team bounds.
    """
    # Mock prisma client
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-123",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request with limits within team bounds
    data = GenerateKeyRequest(
        tpm_limit=5000,
        rpm_limit=500,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
    )

    # Should not raise any exception
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )

    # Verify database was queried
    mock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(
        where={"team_id": "test-team-123"}
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_with_existing_keys_within_bounds():
    """
    Test _check_team_key_limits when team has existing keys but total allocation
    is still within team limits.
    """
    # Create mock existing keys
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 3000
    existing_key1.rpm_limit = 200

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 2000
    existing_key2.rpm_limit = 300

    existing_key3 = MagicMock()
    existing_key3.tpm_limit = None  # Should be ignored in calculation
    existing_key3.rpm_limit = None  # Should be ignored in calculation

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2, existing_key3]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-456",
        team_alias="test-team",
        tpm_limit=10000,  # Total: 3000 + 2000 + 4000 (new) = 9000 < 10000 ✓
        rpm_limit=1000,  # Total: 200 + 300 + 400 (new) = 900 < 1000 ✓
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request that would still be within bounds
    data = GenerateKeyRequest(
        tpm_limit=4000,
        rpm_limit=400,
    )

    # Should not raise any exception
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_tpm_overallocation():
    """
    Test _check_team_key_limits when new key would cause TPM overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create mock existing keys with high TPM usage
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 6000
    existing_key1.rpm_limit = 100
    existing_key1.metadata = {}

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 3000
    existing_key2.rpm_limit = 200
    existing_key2.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-789",
        team_alias="test-team",
        tpm_limit=10000,  # Allocated: 6000 + 3000 = 9000, New: 2000, Total: 11000 > 10000 ✗
        rpm_limit=1000,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request that would exceed TPM limits
    data = GenerateKeyRequest(
        tpm_limit=2000,
        rpm_limit=100,
        tpm_limit_type="guaranteed_throughput",
    )

    # Should raise HTTPException for TPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        await _check_team_key_limits(
            team_table=team_table,
            data=data,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated TPM limit=9000 + Key TPM limit=2000 is greater than team TPM limit=10000"
        in str(exc_info.value.detail)
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_rpm_overallocation():
    """
    Test _check_team_key_limits when new key would cause RPM overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create mock existing keys with high RPM usage
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 1000
    existing_key1.rpm_limit = 600
    existing_key1.metadata = {}

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 2000
    existing_key2.rpm_limit = 300
    existing_key2.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-101",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,  # Allocated: 600 + 300 = 900, New: 200, Total: 1100 > 1000 ✗
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request that would exceed RPM limits
    data = GenerateKeyRequest(
        tpm_limit=1000,
        rpm_limit=200,
        rpm_limit_type="guaranteed_throughput",
    )

    # Should raise HTTPException for RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        await _check_team_key_limits(
            team_table=team_table,
            data=data,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=900 + Key RPM limit=200 is greater than team RPM limit=1000"
        in str(exc_info.value.detail)
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_on_update_excludes_self():
    """
    Test that _check_team_key_limits excludes the key being updated from the
    allocated totals. Without this, the key's current limits would be
    double-counted: once from find_many and once from data.tpm_limit/rpm_limit.
    """
    from litellm.proxy._types import hash_token as _ht

    # The key being updated is returned by find_many with its current limits.
    # In the DB, token is stored as a SHA-256 hash of the raw key.
    self_key = MagicMock()
    self_key.token = _ht("sk-self-team-key")
    self_key.tpm_limit = 6000
    self_key.rpm_limit = 600
    self_key.metadata = {}

    # Another key in the team
    other_key = MagicMock()
    other_key.token = _ht("sk-other-team-key")
    other_key.tpm_limit = 3000
    other_key.rpm_limit = 300
    other_key.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[self_key, other_key]
    )

    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-self",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Updating the key to 7000 TPM. Other key uses 3000, so total = 10000 <= 10000.
    # Without the fix, this would be 6000 (self) + 3000 (other) + 7000 = 16000 > 10000.
    data = UpdateKeyRequest(
        key="sk-self-team-key",
        tpm_limit=7000,
        rpm_limit=700,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
    )

    # Should not raise - the key's own limits should be excluded from the sum
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_no_team_limits():
    """
    Test _check_team_key_limits when team has no TPM/RPM limits set.
    Should allow any key limits since there are no team constraints.
    """
    # Create mock existing keys
    existing_key = MagicMock()
    existing_key.tpm_limit = 5000
    existing_key.rpm_limit = 500

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key]
    )

    # Create team table with no limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-202",
        team_alias="test-team",
        tpm_limit=None,  # No team limit
        rpm_limit=None,  # No team limit
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request with any limits
    data = GenerateKeyRequest(
        tpm_limit=10000,  # High limit should be allowed
        rpm_limit=2000,  # High limit should be allowed
    )

    # Should not raise any exception
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_no_key_limits():
    """
    Test _check_team_key_limits when new key has no TPM/RPM limits.
    Should not raise any exceptions since no limits are being allocated.
    """
    # Create mock existing keys
    existing_key = MagicMock()
    existing_key.tpm_limit = 8000
    existing_key.rpm_limit = 800

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-303",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request with no limits
    data = GenerateKeyRequest(
        tpm_limit=None,  # No limit being set
        rpm_limit=None,  # No limit being set
    )

    # Should not raise any exception
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_mixed_scenarios():
    """
    Test _check_team_key_limits with mixed scenarios:
    - Some existing keys have limits, others don't
    - New key has only one type of limit
    - Team has only one type of limit
    """
    # Create mock existing keys with mixed limits
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 3000
    existing_key1.rpm_limit = None  # No RPM limit

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = None  # No TPM limit
    existing_key2.rpm_limit = 400

    existing_key3 = MagicMock()
    existing_key3.tpm_limit = 2000
    existing_key3.rpm_limit = 300

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2, existing_key3]
    )

    # Create team table with only TPM limit
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-404",
        team_alias="test-team",
        tpm_limit=10000,  # Allocated: 3000 + 0 + 2000 = 5000, New: 4000, Total: 9000 < 10000 ✓
        rpm_limit=None,  # No team RPM limit
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request with only TPM limit
    data = GenerateKeyRequest(
        tpm_limit=4000,
        rpm_limit=None,  # No RPM limit being set
    )

    # Should not raise any exception
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_team_key_limits_exact_boundary():
    """
    Test _check_team_key_limits when allocation exactly matches team limits.
    Should allow the allocation (boundary case).
    """
    # Create mock existing keys
    existing_key = MagicMock()
    existing_key.tpm_limit = 7000
    existing_key.rpm_limit = 700

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key]
    )

    # Create team table with limits
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-505",
        team_alias="test-team",
        tpm_limit=10000,  # Allocated: 7000, New: 3000, Total: 10000 = 10000 ✓
        rpm_limit=1000,  # Allocated: 700, New: 300, Total: 1000 = 1000 ✓
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
    )

    # Create request that exactly matches remaining capacity
    data = GenerateKeyRequest(
        tpm_limit=3000,
        rpm_limit=300,
    )

    # Should not raise any exception (exact boundary should be allowed)
    await _check_team_key_limits(
        team_table=team_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


def test_check_team_key_model_specific_limits_no_limits():
    """
    Test check_team_key_model_specific_limits when no model-specific limits are set.
    Should return without raising any exceptions.
    """
    # Create existing key with no model-specific limits
    existing_key = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user",
        team_id="test-team-123",
        metadata={},
    )

    keys = [existing_key]

    # Create team table
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-123",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
        metadata={},
    )

    # Create request with no model-specific limits
    data = GenerateKeyRequest(
        model_rpm_limit=None,
        model_tpm_limit=None,
    )

    # Should not raise any exception
    check_team_key_model_specific_limits(
        keys=keys,
        team_table=team_table,
        data=data,
    )


def test_check_team_key_model_specific_limits_rpm_overallocation():
    """
    Test check_team_key_model_specific_limits when model-specific RPM would cause overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create existing keys with model-specific RPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        team_id="test-team-456",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 500,
                "gpt-3.5-turbo": 300,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        team_id="test-team-456",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 300,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create team table with RPM limit
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-456",
        team_alias="test-team",
        tpm_limit=10000,
        rpm_limit=1000,  # Total team RPM limit
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
        metadata={},
    )

    # Create request that would exceed model-specific RPM limits
    # Existing gpt-4: 500 + 300 = 800, New: 300, Total: 1100 > 1000 (team limit)
    data = GenerateKeyRequest(
        model_rpm_limit={
            "gpt-4": 300,  # This would cause overallocation
        },
        model_tpm_limit=None,
    )

    # Should raise HTTPException for model-specific RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_team_key_model_specific_limits(
            keys=keys,
            team_table=team_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=800 + Key RPM limit=300 is greater than team RPM limit=1000"
        in str(exc_info.value.detail)
    )


def test_check_team_key_model_specific_limits_team_model_rpm_overallocation():
    """
    Test check_team_key_model_specific_limits when team has model-specific RPM limits
    in metadata and key allocation would exceed those limits.

    This tests the scenario where team_table.metadata["model_rpm_limit"] is set
    with per-model limits, not just a global team RPM limit.
    """
    # Create existing keys with model-specific RPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        team_id="test-team-789",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 300,
                "gpt-3.5-turbo": 200,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        team_id="test-team-789",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 250,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create team table with model-specific RPM limits in metadata
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-789",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
        metadata={
            "model_rpm_limit": {
                "gpt-4": 700,  # Team-level model-specific limit for gpt-4
                "gpt-3.5-turbo": 500,
            }
        },
    )

    # Create request that would exceed team's model-specific RPM limits
    # Existing gpt-4: 300 + 250 = 550, New: 200, Total: 750 > 700 (team model-specific limit)
    data = GenerateKeyRequest(
        model_rpm_limit={
            "gpt-4": 200,  # This would cause overallocation against team model-specific limit
        },
        model_tpm_limit=None,
    )

    # Should raise HTTPException for team model-specific RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_team_key_model_specific_limits(
            keys=keys,
            team_table=team_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=550 + Key RPM limit=200 is greater than team RPM limit=700"
        in str(exc_info.value.detail)
    )


def test_check_team_key_model_specific_limits_team_model_tpm_overallocation():
    """
    Test check_team_key_model_specific_limits when team has model-specific TPM limits
    in metadata and key allocation would exceed those limits.

    This tests the scenario where team_table.metadata["model_tpm_limit"] is set
    with per-model limits, not just a global team TPM limit.
    """
    # Create existing keys with model-specific TPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        team_id="test-team-101",
        metadata={
            "model_tpm_limit": {
                "gpt-4": 5000,
                "claude-3": 3000,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        team_id="test-team-101",
        metadata={
            "model_tpm_limit": {
                "gpt-4": 3500,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create team table with model-specific TPM limits in metadata
    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-101",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=100.0,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[],
        metadata={
            "model_tpm_limit": {
                "gpt-4": 10000,  # Team-level model-specific limit for gpt-4
                "claude-3": 8000,
            }
        },
    )

    # Create request that would exceed team's model-specific TPM limits
    # Existing gpt-4: 5000 + 3500 = 8500, New: 2000, Total: 10500 > 10000 (team model-specific limit)
    data = GenerateKeyRequest(
        model_rpm_limit=None,
        model_tpm_limit={
            "gpt-4": 2000,  # This would cause overallocation against team model-specific limit
        },
    )

    # Should raise HTTPException for team model-specific TPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_team_key_model_specific_limits(
            keys=keys,
            team_table=team_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated TPM limit=8500 + Key TPM limit=2000 is greater than team TPM limit=10000"
        in str(exc_info.value.detail)
    )


@pytest.mark.asyncio
async def test_generate_key_with_object_permission():
    """
    Test that /key/generate correctly handles object_permission by:
    1. Creating a record in litellm_objectpermissiontable
    2. Passing the returned object_permission_id into the key insert payload
    3. NOT passing the object_permission dict to the key table
    """
    from unittest.mock import patch

    from litellm.proxy._types import (
        GenerateKeyRequest,
        LiteLLM_ObjectPermissionBase,
        LitellmUserRoles,
    )
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _common_key_generation_helper,
    )

    # Mock prisma client
    mock_prisma_client = MagicMock()
    mock_prisma_client.jsonify_object = lambda x: x

    # Mock object permission creation
    mock_object_perm_create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm_key_456")
    )
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = mock_object_perm_create

    # Mock key insertion
    mock_key_insert = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123",
            litellm_budget_table=None,
            created_at="2024-01-01T00:00:00Z",
            updated_at="2024-01-01T00:00:00Z",
        )
    )
    mock_prisma_client.insert_data = mock_key_insert

    # Create request with object_permission
    key_request = GenerateKeyRequest(
        models=["gpt-4"],
        object_permission=LiteLLM_ObjectPermissionBase(
            vector_stores=["vector_store_1"],
            mcp_servers=["mcp_server_1"],
        ),
    )

    mock_admin_auth = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin_user",
    )

    # Patch the prisma_client and other dependencies
    with (
        patch(
            "litellm.proxy.proxy_server.prisma_client",
            mock_prisma_client,
        ),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch(
            "litellm.proxy.proxy_server.premium_user",
            False,
        ),
        patch(
            "litellm.proxy.proxy_server.litellm_proxy_admin_name",
            "admin",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_mcp_servers_against_team",
            new=AsyncMock(
                side_effect=lambda object_permission=None, **kwargs: object_permission
            ),
        ),
    ):
        # Execute
        result = await _common_key_generation_helper(
            data=key_request,
            user_api_key_dict=mock_admin_auth,
            litellm_changed_by=None,
            team_table=None,
        )

    # Verify object permission creation was called
    mock_object_perm_create.assert_awaited_once()

    # Verify key insertion was called
    assert mock_key_insert.call_count == 1
    key_insert_kwargs = mock_key_insert.call_args.kwargs
    key_data = key_insert_kwargs["data"]

    # Verify object_permission_id is in the key data
    assert key_data.get("object_permission_id") == "objperm_key_456"

    # Verify object_permission dict is NOT in the key data
    assert "object_permission" not in key_data


@pytest.mark.asyncio
async def test_generate_key_team_member_inherits_org_skips_membership_check():
    """Regression: a team member creating a key for an org-scoped team must not
    be blocked by the org-membership check.

    When ``organization_id`` is inherited from the key's team (via
    ``apply_enterprise_key_management_params`` -> ``add_team_organization_id``),
    the caller already passed team-level authorization. Requiring an explicit
    ``LiteLLM_OrganizationMembership`` row on top of that broke the normal admin
    workflow (admins only add users to teams). This asserts the org-membership
    check is skipped when the org id came from the caller's team.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _common_key_generation_helper,
    )

    org_id = "org-from-team"

    # Team belongs to an org; caller is a team member but NOT an explicit member
    # of that organization (the regression scenario).
    mock_team_table = MagicMock()
    mock_team_table.organization_id = org_id
    mock_team_table.metadata = None

    mock_validate_org = AsyncMock()
    mock_generate_key = AsyncMock(
        return_value={
            "key": "sk-test-key",
            "expires": None,
            "user_id": "alice",
            "team_id": "team-1",
        }
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", True),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_mcp_servers_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_search_tools_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._validate_caller_can_assign_key_org",
            mock_validate_org,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_org_object",
            new_callable=AsyncMock,
            return_value=MagicMock(litellm_budget_table=None),
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_org_key_limits",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            mock_generate_key,
        ),
    ):
        result = await _common_key_generation_helper(
            data=GenerateKeyRequest(
                user_id="alice",
                team_id="team-1",
                organization_id=org_id,
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_id="alice",
                user_role=LitellmUserRoles.INTERNAL_USER.value,
            ),
            litellm_changed_by=None,
            team_table=mock_team_table,
        )

    # Key creation proceeded for the team member ...
    mock_generate_key.assert_awaited_once()
    assert result is not None
    # ... and the org-membership check was bypassed because organization_id was
    # inherited from the caller's team.
    mock_validate_org.assert_not_awaited()


@pytest.mark.asyncio
async def test_generate_key_foreign_org_without_team_still_enforces_membership():
    """VERIA-55: a caller assigning a key to an organization that was NOT
    inherited from a team must still pass the org-membership check.

    This guards the IDOR fix: ``team_table is None`` (or an org id that does not
    match the team) means the org id did not come from team context, so the
    explicit membership validation must run.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _common_key_generation_helper,
    )

    foreign_org_id = "someone-elses-org"

    mock_validate_org = AsyncMock()
    mock_generate_key = AsyncMock(
        return_value={
            "key": "sk-test-key",
            "expires": None,
            "user_id": "alice",
            "team_id": None,
        }
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", True),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._validate_caller_can_assign_key_org",
            mock_validate_org,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_org_object",
            new_callable=AsyncMock,
            return_value=MagicMock(litellm_budget_table=None),
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_org_key_limits",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            mock_generate_key,
        ),
    ):
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                user_id="alice",
                organization_id=foreign_org_id,
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_id="alice",
                user_role=LitellmUserRoles.INTERNAL_USER.value,
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    # No team context -> the org-membership check must still run.
    mock_validate_org.assert_awaited_once()
    assert mock_validate_org.call_args.kwargs["organization_id"] == foreign_org_id


@pytest.mark.asyncio
async def test_generate_key_foreign_org_with_mismatched_team_still_enforces_membership():
    """VERIA-55: when a team is present but its organization_id differs from the
    organization_id on the key request, the org-membership check must still run."""
    from unittest.mock import AsyncMock, MagicMock, patch

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _common_key_generation_helper,
    )

    team_org_id = "other-org"
    foreign_org_id = "someone-elses-org"

    mock_team_table = MagicMock()
    mock_team_table.organization_id = team_org_id
    mock_team_table.metadata = None

    mock_validate_org = AsyncMock()
    mock_generate_key = AsyncMock(
        return_value={
            "key": "sk-test-key",
            "expires": None,
            "user_id": "alice",
            "team_id": "team-1",
        }
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", True),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_mcp_servers_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_search_tools_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm_enterprise.proxy.management_endpoints.key_management_endpoints.apply_enterprise_key_management_params",
            side_effect=lambda data, team_table: data,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._validate_caller_can_assign_key_org",
            mock_validate_org,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_org_object",
            new_callable=AsyncMock,
            return_value=MagicMock(litellm_budget_table=None),
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_org_key_limits",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            mock_generate_key,
        ),
    ):
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                user_id="alice",
                team_id="team-1",
                organization_id=foreign_org_id,
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_id="alice",
                user_role=LitellmUserRoles.INTERNAL_USER.value,
            ),
            litellm_changed_by=None,
            team_table=mock_team_table,
        )

    mock_validate_org.assert_awaited_once()
    assert mock_validate_org.call_args.kwargs["organization_id"] == foreign_org_id


# ============================================
# Organization Key Limit Tests
# ============================================


@pytest.mark.asyncio
async def test_check_org_key_limits_no_existing_keys():
    """
    Test _check_org_key_limits when organization has no existing keys.
    Should allow any TPM/RPM limits within organization bounds.
    """
    # Mock prisma client
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )

    # Create organization table with limits in budget table
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-123",
        organization_alias="test-org",
        budget_id="budget-123",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-123",
            tpm_limit=20000,
            rpm_limit=2000,
        ),
    )

    # Create request with limits within organization bounds
    data = GenerateKeyRequest(
        tpm_limit=10000,
        rpm_limit=1000,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
    )

    # Should not raise any exception
    await _check_org_key_limits(
        org_table=org_table,
        data=data,
        prisma_client=mock_prisma_client,
    )

    # Verify database was queried
    mock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(
        where={"organization_id": "test-org-123"}
    )


@pytest.mark.asyncio
async def test_check_org_key_limits_with_existing_keys_within_bounds():
    """
    Test _check_org_key_limits when organization has existing keys but total allocation
    is still within organization limits.
    """
    # Create mock existing keys
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 5000
    existing_key1.rpm_limit = 400
    existing_key1.metadata = {}

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 3000
    existing_key2.rpm_limit = 500
    existing_key2.metadata = {}

    existing_key3 = MagicMock()
    existing_key3.tpm_limit = None  # Should be ignored in calculation
    existing_key3.rpm_limit = None  # Should be ignored in calculation
    existing_key3.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2, existing_key3]
    )

    # Create organization table with limits
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-456",
        organization_alias="test-org",
        budget_id="budget-456",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-456",
            tpm_limit=20000,  # Total: 5000 + 3000 + 8000 (new) = 16000 < 20000 ✓
            rpm_limit=2000,  # Total: 400 + 500 + 800 (new) = 1700 < 2000 ✓
        ),
    )

    # Create request that would still be within bounds
    data = GenerateKeyRequest(
        tpm_limit=8000,
        rpm_limit=800,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
    )

    # Should not raise any exception
    await _check_org_key_limits(
        org_table=org_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


@pytest.mark.asyncio
async def test_check_org_key_limits_tpm_overallocation():
    """
    Test _check_org_key_limits when new key would cause TPM overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create mock existing keys with high TPM usage
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 12000
    existing_key1.rpm_limit = 500
    existing_key1.metadata = {}

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 6000
    existing_key2.rpm_limit = 400
    existing_key2.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2]
    )

    # Create organization table with limits
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-789",
        organization_alias="test-org",
        budget_id="budget-789",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-789",
            tpm_limit=20000,  # Allocated: 12000 + 6000 = 18000, New: 3000, Total: 21000 > 20000 ✗
            rpm_limit=2000,
        ),
    )

    # Create request that would exceed TPM limits
    data = GenerateKeyRequest(
        tpm_limit=3000,
        rpm_limit=500,
        tpm_limit_type="guaranteed_throughput",
    )

    # Should raise HTTPException for TPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        await _check_org_key_limits(
            org_table=org_table,
            data=data,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated TPM limit=18000 + Key TPM limit=3000 is greater than organization TPM limit=20000"
        in str(exc_info.value.detail)
    )


@pytest.mark.asyncio
async def test_check_org_key_limits_rpm_overallocation():
    """
    Test _check_org_key_limits when new key would cause RPM overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create mock existing keys with high RPM usage
    existing_key1 = MagicMock()
    existing_key1.tpm_limit = 5000
    existing_key1.rpm_limit = 1200
    existing_key1.metadata = {}

    existing_key2 = MagicMock()
    existing_key2.tpm_limit = 3000
    existing_key2.rpm_limit = 600
    existing_key2.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key1, existing_key2]
    )

    # Create organization table with limits
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-101",
        organization_alias="test-org",
        budget_id="budget-101",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-101",
            tpm_limit=20000,
            rpm_limit=2000,  # Allocated: 1200 + 600 = 1800, New: 300, Total: 2100 > 2000 ✗
        ),
    )

    # Create request that would exceed RPM limits
    data = GenerateKeyRequest(
        tpm_limit=5000,
        rpm_limit=300,
        rpm_limit_type="guaranteed_throughput",
    )

    # Should raise HTTPException for RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        await _check_org_key_limits(
            org_table=org_table,
            data=data,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=1800 + Key RPM limit=300 is greater than organization RPM limit=2000"
        in str(exc_info.value.detail)
    )


@pytest.mark.asyncio
async def test_check_org_key_limits_no_org_limits():
    """
    Test _check_org_key_limits when organization has no TPM/RPM limits set.
    Should allow any key limits since there are no organization constraints.
    """
    # Create mock existing keys
    existing_key = MagicMock()
    existing_key.tpm_limit = 10000
    existing_key.rpm_limit = 1000
    existing_key.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key]
    )

    # Create organization table with no limits
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-202",
        organization_alias="test-org",
        budget_id="budget-202",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-202",
            tpm_limit=None,  # No organization limit
            rpm_limit=None,  # No organization limit
        ),
    )

    # Create request with any limits
    data = GenerateKeyRequest(
        tpm_limit=50000,  # High limit should be allowed
        rpm_limit=5000,  # High limit should be allowed
        tpm_limit_type="guaranteed_throughput",
    )

    # Should not raise any exception
    await _check_org_key_limits(
        org_table=org_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


def test_check_org_key_model_specific_limits_no_limits():
    """
    Test check_org_key_model_specific_limits when no model-specific limits are set.
    Should return without raising any exceptions.
    """
    # Create existing key with no model-specific limits
    existing_key = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user",
        organization_id="test-org-123",
        metadata={},
    )

    keys = [existing_key]

    # Create organization table
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-123",
        organization_alias="test-org",
        budget_id="budget-123",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        metadata={},
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-123",
            tpm_limit=20000,
            rpm_limit=2000,
        ),
    )

    # Create request with no model-specific limits
    data = GenerateKeyRequest(
        model_rpm_limit=None,
        model_tpm_limit=None,
    )

    # Should not raise any exception
    check_org_key_model_specific_limits(
        keys=keys,
        org_table=org_table,
        data=data,
    )


def test_check_org_key_model_specific_limits_rpm_overallocation():
    """
    Test check_org_key_model_specific_limits when model-specific RPM would cause overallocation.
    Should raise HTTPException with appropriate error message.
    """
    # Create existing keys with model-specific RPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        organization_id="test-org-456",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 800,
                "gpt-3.5-turbo": 500,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        organization_id="test-org-456",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 600,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create organization table with RPM limit
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-456",
        organization_alias="test-org",
        budget_id="budget-456",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        metadata={},
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-456",
            tpm_limit=20000,
            rpm_limit=2000,  # Total organization RPM limit
        ),
    )

    # Create request that would exceed model-specific RPM limits
    # Existing gpt-4: 800 + 600 = 1400, New: 700, Total: 2100 > 2000 (org limit)
    data = GenerateKeyRequest(
        model_rpm_limit={
            "gpt-4": 700,  # This would cause overallocation
        },
        model_tpm_limit=None,
    )

    # Should raise HTTPException for model-specific RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_org_key_model_specific_limits(
            keys=keys,
            org_table=org_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=1400 + Key RPM limit=700 is greater than organization RPM limit=2000"
        in str(exc_info.value.detail)
    )


def test_check_org_key_model_specific_limits_org_model_rpm_overallocation():
    """
    Test check_org_key_model_specific_limits when organization has model-specific RPM limits
    in metadata and key allocation would exceed those limits.

    This tests the scenario where org_table.metadata["model_rpm_limit"] is set
    with per-model limits, not just a global organization RPM limit.
    """
    # Create existing keys with model-specific RPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        organization_id="test-org-789",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 600,
                "gpt-3.5-turbo": 400,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        organization_id="test-org-789",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 500,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create organization table with model-specific RPM limits in metadata
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-789",
        organization_alias="test-org",
        budget_id="budget-789",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        metadata={
            "model_rpm_limit": {
                "gpt-4": 1400,  # Organization-level model-specific limit for gpt-4
                "gpt-3.5-turbo": 1000,
            }
        },
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-789",
            tpm_limit=None,
            rpm_limit=None,
        ),
    )

    # Create request that would exceed organization's model-specific RPM limits
    # Existing gpt-4: 600 + 500 = 1100, New: 400, Total: 1500 > 1400 (org model-specific limit)
    data = GenerateKeyRequest(
        model_rpm_limit={
            "gpt-4": 400,  # This would cause overallocation against org model-specific limit
        },
        model_tpm_limit=None,
    )

    # Should raise HTTPException for organization model-specific RPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_org_key_model_specific_limits(
            keys=keys,
            org_table=org_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated RPM limit=1100 + Key RPM limit=400 is greater than organization RPM limit=1400"
        in str(exc_info.value.detail)
    )


def test_check_org_key_model_specific_limits_org_model_tpm_overallocation():
    """
    Test check_org_key_model_specific_limits when organization has model-specific TPM limits
    in metadata and key allocation would exceed those limits.

    This tests the scenario where org_table.metadata["model_tpm_limit"] is set
    with per-model limits, not just a global organization TPM limit.
    """
    # Create existing keys with model-specific TPM limits
    existing_key1 = LiteLLM_VerificationToken(
        token="test-token-1",
        user_id="test-user-1",
        organization_id="test-org-101",
        metadata={
            "model_tpm_limit": {
                "gpt-4": 10000,
                "claude-3": 6000,
            }
        },
    )

    existing_key2 = LiteLLM_VerificationToken(
        token="test-token-2",
        user_id="test-user-2",
        organization_id="test-org-101",
        metadata={
            "model_tpm_limit": {
                "gpt-4": 7000,
            }
        },
    )

    keys = [existing_key1, existing_key2]

    # Create organization table with model-specific TPM limits in metadata
    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-101",
        organization_alias="test-org",
        budget_id="budget-101",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        metadata={
            "model_tpm_limit": {
                "gpt-4": 20000,  # Organization-level model-specific limit for gpt-4
                "claude-3": 15000,
            }
        },
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-101",
            tpm_limit=None,
            rpm_limit=None,
        ),
    )

    # Create request that would exceed organization's model-specific TPM limits
    # Existing gpt-4: 10000 + 7000 = 17000, New: 4000, Total: 21000 > 20000 (org model-specific limit)
    data = GenerateKeyRequest(
        model_rpm_limit=None,
        model_tpm_limit={
            "gpt-4": 4000,  # This would cause overallocation against org model-specific limit
        },
    )

    # Should raise HTTPException for organization model-specific TPM overallocation
    with pytest.raises(HTTPException) as exc_info:
        check_org_key_model_specific_limits(
            keys=keys,
            org_table=org_table,
            data=data,
        )

    assert exc_info.value.status_code == 400
    assert (
        "Allocated TPM limit=17000 + Key TPM limit=4000 is greater than organization TPM limit=20000"
        in str(exc_info.value.detail)
    )


def test_transform_verification_tokens_to_deleted_records():
    from datetime import datetime, timezone

    user_api_key_dict = UserAPIKeyAuth(
        user_id="user-123",
        api_key="sk-test",
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
    )

    config_stamp = datetime(2026, 8, 10, 12, 30, 45, tzinfo=timezone.utc)
    key1 = LiteLLM_VerificationToken(
        token="hashed-token-1",
        user_id="user-123",
        team_id="team-456",
        key_alias="test-key-1",
        spend=100.0,
        max_budget=1000.0,
        models=["gpt-4"],
        aliases={},
        config={},
        permissions={},
        metadata={"test": "value"},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
        settings_updated_at=config_stamp,
    )

    key2 = LiteLLM_VerificationToken(
        token="hashed-token-2",
        user_id="user-789",
        team_id=None,
        key_alias="test-key-2",
        spend=50.0,
        max_budget=500.0,
        models=["gpt-3.5-turbo"],
        aliases={"alias": "model"},
        config={"config": "value"},
        permissions={"permission": True},
        metadata={},
        model_max_budget={"gpt-4": {"budget_limit": 100.0}},
        budget_fallbacks={"gpt-4": ["gpt-4o-mini"]},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    records = _transform_verification_tokens_to_deleted_records(
        keys=[key1, key2],
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by="admin-user",
    )

    assert len(records) == 2
    assert all("deleted_at" in record for record in records)
    assert all("deleted_by" in record for record in records)
    assert all("deleted_by_api_key" in record for record in records)
    assert all("litellm_changed_by" in record for record in records)
    assert all(record["deleted_by"] == "user-123" for record in records)
    assert all(
        record["deleted_by_api_key"] == user_api_key_dict.api_key for record in records
    )
    assert all(record["litellm_changed_by"] == "admin-user" for record in records)

    record1 = records[0]
    assert record1["token"] == "hashed-token-1"
    assert record1["user_id"] == "user-123"
    assert record1["team_id"] == "team-456"
    assert record1["settings_updated_at"] == config_stamp
    assert isinstance(record1["aliases"], str)
    assert isinstance(record1["config"], str)
    assert isinstance(record1["permissions"], str)
    assert isinstance(record1["metadata"], str)
    assert "litellm_budget_table" not in record1
    assert "litellm_organization_table" not in record1
    assert "object_permission" not in record1
    assert "id" not in record1

    record2 = records[1]
    assert record2["token"] == "hashed-token-2"
    assert isinstance(record2["model_max_budget"], str)
    assert isinstance(record2["budget_fallbacks"], str)
    assert json.loads(record2["budget_fallbacks"]) == {"gpt-4": ["gpt-4o-mini"]}


def test_transform_verification_tokens_to_deleted_records_keeps_organization_id():
    live_row = MagicMock()
    live_row.model_dump.return_value = {
        "token": "hashed-token-org",
        "user_id": "user-123",
        "team_id": None,
        "organization_id": "org-finops",
    }

    records = _transform_verification_tokens_to_deleted_records(
        keys=[live_row],
        user_api_key_dict=UserAPIKeyAuth(user_id="admin-1", api_key="sk-admin"),
    )

    assert records[0]["organization_id"] == "org-finops"


def test_transform_verification_tokens_to_deleted_records_empty_list():
    user_api_key_dict = UserAPIKeyAuth(
        user_id="user-123",
        api_key="sk-test",
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
    )

    records = _transform_verification_tokens_to_deleted_records(
        keys=[],
        user_api_key_dict=user_api_key_dict,
    )

    assert records == []


@pytest.mark.asyncio
async def test_save_deleted_verification_token_records():
    mock_prisma_client = AsyncMock()
    mock_create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (
        mock_create_many
    )

    records = [
        {
            "token": "hashed-token-1",
            "user_id": "user-123",
            "deleted_at": "2024-01-01T00:00:00Z",
            "deleted_by": "admin",
        },
        {
            "token": "hashed-token-2",
            "user_id": "user-456",
            "deleted_at": "2024-01-01T00:00:00Z",
            "deleted_by": "admin",
        },
    ]

    await _save_deleted_verification_token_records(
        records=records, prisma_client=mock_prisma_client
    )

    mock_create_many.assert_called_once_with(data=records)


@pytest.mark.asyncio
async def test_save_deleted_verification_token_records_empty_list():
    mock_prisma_client = AsyncMock()
    mock_create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (
        mock_create_many
    )

    await _save_deleted_verification_token_records(
        records=[], prisma_client=mock_prisma_client
    )

    mock_create_many.assert_not_called()


@pytest.mark.asyncio
async def test_persist_deleted_verification_tokens():
    mock_prisma_client = AsyncMock()
    mock_create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (
        mock_create_many
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_id="user-123",
        api_key="sk-test",
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
    )

    key = LiteLLM_VerificationToken(
        token="hashed-token-1",
        user_id="user-123",
        team_id="team-456",
        key_alias="test-key",
        spend=100.0,
        max_budget=1000.0,
        models=["gpt-4"],
        aliases={},
        config={},
        permissions={},
        metadata={},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    await persist_deleted_verification_tokens(
        keys=[key],
        prisma_client=mock_prisma_client,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by="admin-user",
    )

    mock_create_many.assert_called_once()
    call_args = mock_create_many.call_args
    assert "data" in call_args.kwargs
    records = call_args.kwargs["data"]
    assert len(records) == 1
    assert records[0]["token"] == "hashed-token-1"
    assert records[0]["deleted_by"] == "user-123"
    assert records[0]["litellm_changed_by"] == "admin-user"


@pytest.mark.asyncio
async def test_delete_verification_tokens_persists_deleted_keys(monkeypatch):
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_id="admin-user",
        api_key="sk-admin",
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
    )

    key1 = LiteLLM_VerificationToken(
        token="hashed-token-1",
        user_id="user-123",
        team_id="team-456",
        key_alias="test-key-1",
        spend=100.0,
        max_budget=1000.0,
        models=["gpt-4"],
        aliases={},
        config={},
        permissions={},
        metadata={},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    key2 = LiteLLM_VerificationToken(
        token="hashed-token-2",
        user_id="user-789",
        team_id=None,
        key_alias="test-key-2",
        spend=50.0,
        max_budget=500.0,
        models=["gpt-3.5-turbo"],
        aliases={},
        config={},
        permissions={},
        metadata={},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    mock_find_many = AsyncMock(return_value=[key1, key2])
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many

    # delete_data returns {"deleted_keys": ...} from utils.py line 3049
    # The function at line 2410 assigns it to deleted_tokens
    # Then at line 2444 returns {"deleted_keys": deleted_tokens}
    # So if delete_data returns {"deleted_keys": list}, then result would be nested
    # But looking at the error, it seems like delete_data might return just the list
    # Or the code extracts it. Let's return the list directly since that's what the test expects
    mock_delete_data = AsyncMock(return_value=["hashed-token-1", "hashed-token-2"])
    mock_prisma_client.delete_data = mock_delete_data

    # Mock cache delete_cache method
    mock_user_api_key_cache.delete_cache = MagicMock()

    mock_create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = (
        mock_create_many
    )

    def mock_hash_token(token):
        return token if not token.startswith("sk-") else f"hashed-{token}"

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
        mock_hash_token,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token",
        mock_hash_token,
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        mock_prisma_client,
    )

    result, deleted_keys = await delete_verification_tokens(
        tokens=["sk-token-1", "sk-token-2"],
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by="admin-user",
    )

    mock_create_many.assert_called_once()
    call_args = mock_create_many.call_args
    assert "data" in call_args.kwargs
    records = call_args.kwargs["data"]
    assert len(records) == 2
    assert all(record["deleted_by"] == "admin-user" for record in records)
    assert all(record["litellm_changed_by"] == "admin-user" for record in records)
    # delete_data returns the list directly, which gets wrapped in {"deleted_keys": ...}
    assert isinstance(result["deleted_keys"], list)
    assert set(result["deleted_keys"]) == {"hashed-token-1", "hashed-token-2"}
    assert len(deleted_keys) == 2


class _JWTMappingRow:
    def __init__(self, token, jwt_claim_name, jwt_claim_value, jwt_issuer=None):
        self.token = token
        self.jwt_claim_name = jwt_claim_name
        self.jwt_claim_value = jwt_claim_value
        self.jwt_issuer = jwt_issuer


class _CascadingJWTMappingTable:
    """Mapping rows that LiteLLM_JWTKeyMapping_token_fkey drops when their key is deleted."""

    def __init__(self, rows):
        self.rows = rows

    async def find_many(self, where, **kwargs):
        return [row for row in self.rows if row.token == where["token"]]

    def cascade(self, deleted_tokens):
        self.rows = [row for row in self.rows if row.token not in deleted_tokens]


class _RecordingEvict:
    def __init__(self):
        self.cache_keys = ()

    async def __call__(self, cache_keys, user_api_key_cache):
        self.cache_keys = tuple(cache_keys)


@pytest.mark.asyncio
async def test_delete_verification_tokens_evicts_jwt_key_mapping_cache(monkeypatch):
    """Deleting a key must evict its jwt_key_mapping cache entries (LIT-5380).

    The FK cascade removes the mapping rows, so a surviving cache entry would keep
    resolving the deleted token hash and 401 every JWT call from that identity until
    virtual_key_mapping_cache_ttl expires, instead of auto-registering again.
    """
    jwt_table = _CascadingJWTMappingTable(
        [
            _JWTMappingRow("hashed-token-1", "email", "[email protected]"),
            _JWTMappingRow("hashed-token-1", "email", "[email protected]", "https://issuer.example"),
        ]
    )

    key1 = LiteLLM_VerificationToken(
        token="hashed-token-1",
        user_id="user-123",
        team_id=None,
        key_alias="jwt-mapped-key",
        spend=0.0,
        max_budget=None,
        models=[],
        aliases={},
        config={},
        permissions={},
        metadata={},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[key1]
    )
    mock_prisma_client.db.litellm_jwtkeymapping = jwt_table
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()

    async def cascading_delete_data(tokens):
        jwt_table.cascade(tokens)
        return list(tokens)

    mock_prisma_client.delete_data = AsyncMock(side_effect=cascading_delete_data)

    recording_evict = _RecordingEvict()
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.evict_and_broadcast",
        recording_evict,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
        lambda token: token,
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        mock_prisma_client,
    )

    await delete_verification_tokens(
        tokens=["hashed-token-1"],
        user_api_key_cache=MagicMock(),
        user_api_key_dict=UserAPIKeyAuth(
            user_id="admin-user",
            api_key="sk-admin",
            user_role=LitellmUserRoles.PROXY_ADMIN.value,
        ),
    )

    assert recording_evict.cache_keys == (
        jwt_key_mapping_cache_key("email", "[email protected]", None),
        jwt_key_mapping_cache_key("email", "[email protected]", "https://issuer.example"),
    )


@pytest.mark.asyncio
async def test_delete_key_fn_persists_deleted_keys(monkeypatch):
    from litellm.proxy._types import KeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        delete_key_fn,
        delete_verification_tokens,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_id="admin-user",
        api_key="sk-admin",
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
    )

    key1 = LiteLLM_VerificationToken(
        token="hashed-token-1",
        user_id="user-123",
        team_id="team-456",
        key_alias="test-key-1",
        spend=100.0,
        max_budget=1000.0,
        models=["gpt-4"],
        aliases={},
        config={},
        permissions={},
        metadata={},
        model_max_budget={},
        model_spend={},
        soft_budget_cooldown=False,
        allowed_routes=[],
    )

    async def mock_delete_verification_tokens(*args, **kwargs):
        return ({"deleted_keys": ["sk-token-1"]}, [key1])

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_verification_tokens",
        mock_delete_verification_tokens,
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        mock_prisma_client,
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache",
        mock_user_api_key_cache,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_deleted_hook",
        AsyncMock(),
    )

    data = KeyRequest(keys=["sk-token-1"])

    result = await delete_key_fn(
        data=data,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by="admin-user",
    )

    assert result["deleted_keys"] == ["sk-token-1"]


@pytest.mark.asyncio
async def test_can_delete_verification_token_proxy_admin_team_key(monkeypatch):
    """Test that team admin can delete team keys from their own team."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="other-user",
        team_id="test-team-123",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="team-admin-user",
        api_key="sk-user",
    )

    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-123",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="team-admin-user", role="admin"),
            Member(user_id="other-user", role="user"),
        ],
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is True


@pytest.mark.asyncio
async def test_can_delete_verification_token_team_admin_different_team(monkeypatch):
    """Test that team admin cannot delete team keys from a different team."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="other-user",
        team_id="test-team-456",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="team-admin-user",
        api_key="sk-user",
    )

    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-456",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="different-admin", role="admin"),
            Member(user_id="other-user", role="user"),
        ],
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is False


@pytest.mark.asyncio
async def test_can_delete_verification_token_key_owner_team_key(monkeypatch):
    """Test that key owner can delete their own team key."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="key-owner-user",
        team_id="test-team-123",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="key-owner-user",
        api_key="sk-user",
    )

    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-123",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="key-owner-user", role="user"),
        ],
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is True


@pytest.mark.asyncio
async def test_can_delete_verification_token_key_owner_personal_key(monkeypatch):
    """Test that key owner can delete their own personal key."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="key-owner-user",
        team_id=None,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="key-owner-user",
        api_key="sk-user",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is True


@pytest.mark.asyncio
async def test_can_delete_verification_token_other_user_team_key(monkeypatch):
    """Test that other user cannot delete team keys they don't own and aren't admin for."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="key-owner-user",
        team_id="test-team-123",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="other-user",
        api_key="sk-user",
    )

    team_table = LiteLLM_TeamTableCachedObj(
        team_id="test-team-123",
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="key-owner-user", role="user"),
            Member(user_id="other-user", role="user"),
            Member(user_id="team-admin-user", role="admin"),
        ],
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is False


@pytest.mark.asyncio
async def test_can_delete_verification_token_other_user_personal_key(monkeypatch):
    """Test that other user cannot delete personal keys they don't own."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="key-owner-user",
        team_id=None,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="other-user",
        api_key="sk-user",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is False


@pytest.mark.asyncio
async def test_can_delete_verification_token_team_key_no_team_found(monkeypatch):
    """Test that deletion fails when team is not found in database."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="key-owner-user",
        team_id="non-existent-team",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="key-owner-user",
        api_key="sk-user",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    async def mock_get_team_object(*args, **kwargs):
        return None

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is False


@pytest.mark.asyncio
async def test_can_delete_verification_token_personal_key_no_user_id(monkeypatch):
    """Test that deletion fails for personal key when key has no user_id."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id=None,
        team_id=None,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="some-user",
        api_key="sk-user",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is False


@pytest.mark.asyncio
async def test_can_modify_verification_token_proxy_admin_team_key(monkeypatch):
    """Test that proxy admin can modify any team key."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="other-user",
        team_id="test-team-123",
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-user",
        api_key="sk-admin",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is True


@pytest.mark.asyncio
async def test_can_modify_verification_token_proxy_admin_personal_key(monkeypatch):
    """Test that proxy admin can modify any personal key."""
    key_info = LiteLLM_VerificationToken(
        token="test-token",
        user_id="other-user",
        team_id=None,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-user",
        api_key="sk-admin",
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()

    result = await can_modify_verification_token(
        key_info=key_info,
        user_api_key_cache=mock_user_api_key_cache,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    assert result is True


@pytest.mark.asyncio
async def test_list_keys_with_expand_user():
    """
    Test that expand=user parameter correctly includes user information in the response.
    """
    mock_prisma_client = AsyncMock()

    # Create mock keys with user_ids
    key1_dict = {
        "token": "token1",
        "user_id": "user123",
        "key_alias": "key1",
        "models": ["gpt-4"],
    }
    mock_key1 = MagicMock()
    mock_key1.token = "token1"
    mock_key1.user_id = "user123"
    mock_key1.created_by = None
    # Set up model_dump() to raise AttributeError so it falls back to dict()
    mock_key1.model_dump = MagicMock(
        side_effect=AttributeError("model_dump not available")
    )
    mock_key1.dict = MagicMock(return_value=key1_dict)

    key2_dict = {
        "token": "token2",
        "user_id": "user456",
        "key_alias": "key2",
        "models": ["gpt-3.5-turbo"],
    }
    mock_key2 = MagicMock()
    mock_key2.token = "token2"
    mock_key2.user_id = "user456"
    mock_key2.created_by = None
    # Set up model_dump() to raise AttributeError so it falls back to dict()
    mock_key2.model_dump = MagicMock(
        side_effect=AttributeError("model_dump not available")
    )
    mock_key2.dict = MagicMock(return_value=key2_dict)

    mock_find_many_keys = AsyncMock(return_value=[mock_key1, mock_key2])
    mock_count_keys = AsyncMock(return_value=2)

    # Create mock users
    user1_dict = {
        "user_id": "user123",
        "user_email": "[email protected]",
        "user_alias": "User One",
    }
    mock_user1 = MagicMock()
    # Set user_id as a real attribute (not a MagicMock)
    mock_user1.user_id = "user123"
    mock_user1.user_email = "[email protected]"
    # Set up both model_dump() and dict() to return the same dict
    mock_user1.model_dump = MagicMock(return_value=user1_dict)
    mock_user1.dict = MagicMock(return_value=user1_dict)

    user2_dict = {
        "user_id": "user456",
        "user_email": "[email protected]",
        "user_alias": "User Two",
    }
    mock_user2 = MagicMock()
    # Set user_id as a real attribute (not a MagicMock)
    mock_user2.user_id = "user456"
    mock_user2.user_email = "[email protected]"
    # Set up both model_dump() and dict() to return the same dict
    mock_user2.model_dump = MagicMock(return_value=user2_dict)
    mock_user2.dict = MagicMock(return_value=user2_dict)

    mock_find_many_users = AsyncMock(return_value=[mock_user1, mock_user2])

    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many_keys
    mock_prisma_client.db.litellm_verificationtoken.count = mock_count_keys
    mock_prisma_client.db.litellm_usertable.find_many = mock_find_many_users

    # Patch attach_object_permission_to_dict to just return the dict unchanged
    async def mock_attach_object_permission(d, _):
        return d

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.attach_object_permission_to_dict",
        side_effect=mock_attach_object_permission,
    ):
        args = {
            "prisma_client": mock_prisma_client,
            "page": 1,
            "size": 50,
            "user_id": None,
            "team_id": None,
            "organization_id": None,
            "key_alias": None,
            "key_hash": None,
            "exclude_team_id": None,
            "return_full_object": False,  # This should be overridden by expand=user
            "admin_team_ids": None,
            "include_created_by_keys": False,
            "expand": ["user"],  # Test the expand parameter
        }

        result = await list_key_helper(**args)

        # Verify that keys were fetched
        mock_find_many_keys.assert_called_once()
        mock_count_keys.assert_called_once()

        # Verify that users were fetched
        # Note: Order doesn't matter for the 'in' query, so we just check that both user_ids are present
        call_args = mock_find_many_users.call_args
        assert call_args is not None
        where_clause = call_args.kwargs["where"]
        assert "user_id" in where_clause
        assert "in" in where_clause["user_id"]
        user_ids_in_query = set(where_clause["user_id"]["in"])
        assert user_ids_in_query == {"user123", "user456"}

        # Verify response structure
        assert len(result["keys"]) == 2
        assert result["total_count"] == 2
        assert result["current_page"] == 1
        assert result["total_pages"] == 1

        # Verify that user data is included in the response
        # Since expand=user is specified, keys should be full objects
        assert isinstance(result["keys"][0], UserAPIKeyAuth)
        assert isinstance(result["keys"][1], UserAPIKeyAuth)

        # Verify user data is attached to keys
        assert result["keys"][0].user == {
            "user_id": "user123",
            "user_email": "[email protected]",
            "user_alias": "User One",
        }
        assert result["keys"][1].user == {
            "user_id": "user456",
            "user_email": "[email protected]",
            "user_alias": "User Two",
        }


@pytest.mark.asyncio
async def test_list_keys_with_expand_user_includes_created_by_user():
    """
    Test that expand=user also resolves created_by to a user object.
    """
    mock_prisma_client = AsyncMock()

    # Key created by user789 but owned by user123
    key1_dict = {
        "token": "token1",
        "user_id": "user123",
        "created_by": "user789",
        "key_alias": "key1",
        "models": ["gpt-4"],
    }
    mock_key1 = MagicMock()
    mock_key1.token = "token1"
    mock_key1.user_id = "user123"
    mock_key1.created_by = "user789"
    mock_key1.model_dump = MagicMock(return_value=key1_dict)

    mock_find_many_keys = AsyncMock(return_value=[mock_key1])
    mock_count_keys = AsyncMock(return_value=1)

    # Create mock users for both user_id and created_by
    mock_user_owner = MagicMock()
    mock_user_owner.user_id = "user123"
    mock_user_owner.user_email = "[email protected]"
    mock_user_owner.user_alias = "Owner"
    mock_user_owner.model_dump = MagicMock(
        return_value={
            "user_id": "user123",
            "user_email": "[email protected]",
            "user_alias": "Owner",
        }
    )

    mock_user_creator = MagicMock()
    mock_user_creator.user_id = "user789"
    mock_user_creator.user_email = "[email protected]"
    mock_user_creator.user_alias = "Creator"

    mock_find_many_users = AsyncMock(return_value=[mock_user_owner, mock_user_creator])

    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many_keys
    mock_prisma_client.db.litellm_verificationtoken.count = mock_count_keys
    mock_prisma_client.db.litellm_usertable.find_many = mock_find_many_users

    async def mock_attach_object_permission(d, _):
        return d

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.attach_object_permission_to_dict",
        side_effect=mock_attach_object_permission,
    ):
        args = {
            "prisma_client": mock_prisma_client,
            "page": 1,
            "size": 50,
            "user_id": None,
            "team_id": None,
            "organization_id": None,
            "key_alias": None,
            "key_hash": None,
            "exclude_team_id": None,
            "return_full_object": False,
            "admin_team_ids": None,
            "include_created_by_keys": False,
            "expand": ["user"],
        }

        result = await list_key_helper(**args)

        # Verify that the user lookup included both user_id and created_by
        call_args = mock_find_many_users.call_args
        user_ids_in_query = set(call_args.kwargs["where"]["user_id"]["in"])
        assert user_ids_in_query == {"user123", "user789"}

        # Verify created_by_user is attached
        key_result = result["keys"][0]
        assert key_result.created_by_user == {
            "user_id": "user789",
            "user_email": "[email protected]",
            "user_alias": "Creator",
        }

        # Verify user (owner) is also still attached
        assert key_result.user == {
            "user_id": "user123",
            "user_email": "[email protected]",
            "user_alias": "Owner",
        }


@pytest.mark.asyncio
async def test_list_keys_with_status_deleted():
    """
    Test that status="deleted" parameter correctly queries the deleted keys table.
    """
    mock_prisma_client = AsyncMock()

    # Mock deleted keys table
    mock_deleted_key1 = MagicMock()
    mock_deleted_key1.token = "deleted_token1"
    mock_deleted_key1.user_id = "user123"
    mock_deleted_key1.dict.return_value = {
        "token": "deleted_token1",
        "user_id": "user123",
        "key_alias": "deleted_key1",
    }

    mock_deleted_key2 = MagicMock()
    mock_deleted_key2.token = "deleted_token2"
    mock_deleted_key2.user_id = "user456"
    mock_deleted_key2.dict.return_value = {
        "token": "deleted_token2",
        "user_id": "user456",
        "key_alias": "deleted_key2",
    }

    mock_find_many_deleted = AsyncMock(
        return_value=[mock_deleted_key1, mock_deleted_key2]
    )
    mock_count_deleted = AsyncMock(return_value=2)

    # Mock regular keys table (should not be called)
    mock_find_many_regular = AsyncMock(return_value=[])
    mock_count_regular = AsyncMock(return_value=0)

    mock_prisma_client.db.litellm_deletedverificationtoken.find_many = (
        mock_find_many_deleted
    )
    mock_prisma_client.db.litellm_deletedverificationtoken.count = mock_count_deleted
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many_regular
    mock_prisma_client.db.litellm_verificationtoken.count = mock_count_regular

    args = {
        "prisma_client": mock_prisma_client,
        "page": 1,
        "size": 50,
        "user_id": None,
        "team_id": None,
        "organization_id": None,
        "key_alias": None,
        "key_hash": None,
        "exclude_team_id": None,
        "return_full_object": False,
        "admin_team_ids": None,
        "include_created_by_keys": False,
        "status": "deleted",  # Test the status parameter
    }

    result = await list_key_helper(**args)

    # Verify that deleted table was queried
    mock_find_many_deleted.assert_called_once()
    mock_count_deleted.assert_called_once()

    # Verify that regular table was NOT queried
    mock_find_many_regular.assert_not_called()
    mock_count_regular.assert_not_called()

    # Verify response structure
    assert len(result["keys"]) == 2
    assert result["total_count"] == 2
    assert result["current_page"] == 1
    assert result["total_pages"] == 1


@pytest.mark.asyncio
async def test_list_keys_with_invalid_status():
    """
    Test that invalid status parameter raises ProxyException.
    """
    from unittest.mock import Mock, patch

    mock_prisma_client = AsyncMock()

    # Mock the endpoint function directly to test validation
    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import list_keys
    from litellm.proxy.utils import ProxyException

    mock_request = Mock()
    mock_user_api_key_dict = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)

    # Mock prisma_client to be non-None
    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        # Should raise ProxyException for invalid status (HTTPException is caught and re-raised as ProxyException)
        with pytest.raises(ProxyException) as exc_info:
            await list_keys(
                request=mock_request,
                user_api_key_dict=mock_user_api_key_dict,
                status="invalid_status",  # Invalid status value
            )

        # Verify ProxyException properties
        assert exc_info.value.code == "400"
        assert "Invalid status value" in str(exc_info.value.message)
        assert "deleted" in str(exc_info.value.message)


@pytest.mark.asyncio
@pytest.mark.parametrize("status_filter", ["active", "expired", "revoked"])
async def test_list_keys_accepts_live_status_filters(monkeypatch, status_filter):
    from unittest.mock import Mock

    from litellm.proxy.management_endpoints.key_management_endpoints import list_keys

    live_row = MagicMock()
    live_row.model_dump.return_value = {"token": "hashed_live_token", "object_permission_id": None}
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[live_row])
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=1)
    mock_prisma_client.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    response = await list_keys(
        request=Mock(),
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
        page=1,
        size=10,
        user_id=None,
        team_id=None,
        organization_id=None,
        key_hash=None,
        key_alias=None,
        search=None,
        return_full_object=False,
        include_team_keys=False,
        include_created_by_keys=False,
        sort_by=None,
        sort_order="desc",
        expand=None,
        status=status_filter,
        project_id=None,
        access_group_id=None,
        agent_id=None,
        substring_matching=False,
        expires=None,
    )

    assert response["keys"] == ["hashed_live_token"]
    assert response["total_count"] == 1
    mock_prisma_client.db.litellm_deletedverificationtoken.find_many.assert_not_called()


def _status_filter_where(status_filter: str | None) -> Mapping[str, object]:
    from litellm.proxy.management_endpoints.key_management_endpoints import _build_key_filter_conditions

    return _build_key_filter_conditions(
        user_id=None,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        status_filter=status_filter,
    )


def test_build_key_filter_conditions_status_filter_partitions_live_keys():
    not_blocked = {"OR": [{"blocked": None}, {"blocked": False}]}

    revoked_where = _status_filter_where("revoked")
    assert {"blocked": True} in revoked_where["AND"]

    expired_clause = next(clause for clause in _status_filter_where("expired")["AND"] if "AND" in clause)
    assert expired_clause["AND"][0] == not_blocked
    assert expired_clause["AND"][1]["AND"][0] == {"expires": {"not": None}}
    assert "lt" in expired_clause["AND"][1]["AND"][1]["expires"]

    active_clause = next(clause for clause in _status_filter_where("active")["AND"] if "AND" in clause)
    assert active_clause["AND"][0] == not_blocked
    assert active_clause["AND"][1]["OR"][0] == {"expires": None}
    assert "gte" in active_clause["AND"][1]["OR"][1]["expires"]


def test_build_key_filter_conditions_deleted_status_adds_no_live_clause():
    assert _status_filter_where("deleted") == _status_filter_where(None)


@pytest.mark.asyncio
async def test_list_key_helper_revoked_status_filters_live_table_on_blocked():
    mock_prisma_client = AsyncMock()
    mock_find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_deletedverificationtoken.find_many = AsyncMock(return_value=[])

    await list_key_helper(
        prisma_client=mock_prisma_client,
        page=1,
        size=50,
        user_id=None,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        return_full_object=True,
        admin_team_ids=None,
        include_created_by_keys=False,
        status="revoked",
    )

    mock_prisma_client.db.litellm_deletedverificationtoken.find_many.assert_not_called()
    where = mock_find_many.call_args.kwargs["where"]
    assert {"blocked": True} in where["AND"]


def _archived_key_row(token: str, user_id: str) -> MagicMock:
    row = MagicMock()
    row.model_dump.return_value = {
        "id": "archive-row-1",
        "token": token,
        "key_alias": "finops-2024",
        "user_id": user_id,
        "team_id": None,
        "organization_id": "org-finops",
        "blocked": None,
        "deleted_at": datetime(2024, 11, 15, 10, 0, tzinfo=timezone.utc),
        "deleted_by": "admin-1",
    }
    return row


@pytest.mark.asyncio
async def test_info_key_fn_serves_deleted_key_from_archive(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    hashed = "hashed_deleted_token"
    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_deletedverificationtoken.find_first = AsyncMock(
        return_value=_archived_key_row(hashed, "user-x")
    )

    result = await info_key_fn(
        key=hashed,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
    )

    mock_prisma_client.db.litellm_deletedverificationtoken.find_first.assert_awaited_once()
    assert mock_prisma_client.db.litellm_deletedverificationtoken.find_first.await_args.kwargs["where"] == {
        "token": hashed
    }
    info = result["info"]
    assert info["status"] == "deleted"
    assert info["key_alias"] == "finops-2024"
    assert info["organization_id"] == "org-finops"
    assert info["deleted_by"] == "admin-1"
    assert info["deleted_at"] is not None
    assert "token" not in info


@pytest.mark.asyncio
async def test_info_key_fn_archived_key_keeps_owner_authorization(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    hashed = "hashed_deleted_token"
    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_deletedverificationtoken.find_first = AsyncMock(
        return_value=_archived_key_row(hashed, "owner-1")
    )

    with pytest.raises(ProxyException) as exc_info:
        await info_key_fn(
            key=hashed,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER, user_id="someone-else", api_key="sk-other"
            ),
        )
    assert exc_info.value.code == "403"

    owner_result = await info_key_fn(
        key=hashed,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="owner-1", api_key="sk-own"),
    )
    assert owner_result["info"]["status"] == "deleted"


@pytest.mark.asyncio
async def test_info_key_fn_unknown_key_still_404s(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_deletedverificationtoken.find_first = AsyncMock(return_value=None)

    with pytest.raises(ProxyException) as exc_info:
        await info_key_fn(
            key="hashed_missing",
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
        )
    assert exc_info.value.code == "404"


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("blocked", "expires", "expected_status"),
    [
        (True, None, "revoked"),
        (True, "2020-01-01T00:00:00Z", "revoked"),
        (False, "2020-01-01T00:00:00Z", "expired"),
        (None, datetime(2020, 1, 1, tzinfo=timezone.utc), "expired"),
        (False, None, "active"),
        (None, "2999-01-01T00:00:00Z", "active"),
    ],
)
async def test_info_key_fn_reports_live_key_status(monkeypatch, blocked, expires, expected_status):
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    live_row = MagicMock(spec=LiteLLM_VerificationToken)
    live_row.model_dump.return_value = {
        "token": "hashed_live",
        "user_id": "user-x",
        "team_id": None,
        "object_permission_id": None,
        "blocked": blocked,
        "expires": expires,
    }
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=live_row)

    result = await info_key_fn(
        key="hashed_live",
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
    )

    assert result["info"]["status"] == expected_status
    mock_prisma_client.db.litellm_deletedverificationtoken.find_first.assert_not_called()


@pytest.mark.asyncio
async def test_list_keys_non_admin_user_id_auto_set():
    """
    Test that when a non-admin user calls list_keys with user_id=None,
    the user_id is automatically set to the authenticated user's user_id.
    """
    from unittest.mock import Mock, patch

    mock_prisma_client = AsyncMock()

    # Create a non-admin user with a user_id
    test_user_id = "test-user-123"
    mock_user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=test_user_id,
    )

    # Mock user info returned by validate_key_list_check
    mock_user_info = LiteLLM_UserTable(
        user_id=test_user_id,
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )

    # Mock _list_key_helper to capture the user_id argument
    mock_list_key_helper = AsyncMock(
        return_value={
            "keys": [],
            "total_count": 0,
            "current_page": 1,
            "total_pages": 0,
        }
    )

    # Mock prisma_client to be non-None
    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_list_check",
            return_value=mock_user_info,
        ):
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.get_admin_team_ids",
                return_value=[],
            ):
                with patch(
                    "litellm.proxy.management_endpoints.key_management_endpoints.list_key_helper",
                    mock_list_key_helper,
                ):
                    mock_request = Mock()

                    # Call list_keys with user_id=None
                    await list_keys(
                        request=mock_request,
                        user_api_key_dict=mock_user_api_key_dict,
                        user_id=None,  # This should be auto-set to test_user_id
                        status=None,  # Explicitly set status to None to avoid validation errors
                    )

                    # Verify that _list_key_helper was called with user_id set to the authenticated user's user_id
                    mock_list_key_helper.assert_called_once()
                    call_kwargs = mock_list_key_helper.call_args.kwargs
                    assert call_kwargs["user_id"] == test_user_id, (
                        f"Expected user_id to be set to {test_user_id}, "
                        f"but got {call_kwargs.get('user_id')}"
                    )


def _make_member_team_table(
    team_id: str,
    member_user_id: str,
    member_role: str = "user",
    team_member_permissions=None,
):
    """Build a LiteLLM_TeamTable with a single member, suitable for list_keys tests."""
    from litellm.proxy._types import LiteLLM_TeamTable, Member

    return LiteLLM_TeamTable(
        team_id=team_id,
        members_with_roles=[Member(user_id=member_user_id, role=member_role)],
        team_member_permissions=team_member_permissions,
    )


async def _invoke_list_keys_and_capture_helper_kwargs(
    user_api_key_dict,
    team_objects,
    *,
    include_team_keys: bool = True,
):
    """
    Invoke list_keys with mocked dependencies and return the kwargs that
    list_keys passes to _list_key_helper (so tests can assert on
    admin_team_ids / member_team_ids classification).
    """
    from unittest.mock import Mock, patch

    from litellm.proxy._types import LiteLLM_UserTable

    mock_prisma_client = AsyncMock()
    mock_user_info = LiteLLM_UserTable(
        user_id=user_api_key_dict.user_id,
        user_email="[email protected]",
        teams=[t.team_id for t in team_objects],
        organization_memberships=[],
    )
    mock_list_key_helper = AsyncMock(
        return_value={
            "keys": [],
            "total_count": 0,
            "current_page": 1,
            "total_pages": 0,
        }
    )
    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_list_check",
            return_value=mock_user_info,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._fetch_user_team_objects",
            AsyncMock(return_value=team_objects),
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.list_key_helper",
            mock_list_key_helper,
        ),
    ):
        await list_keys(
            request=Mock(),
            user_api_key_dict=user_api_key_dict,
            include_team_keys=include_team_keys,
            status=None,
        )
    mock_list_key_helper.assert_called_once()
    return mock_list_key_helper.call_args.kwargs


@pytest.mark.asyncio
async def test_list_keys_team_member_with_key_list_permission_sees_all_team_keys():
    """
    Bug fix: when a team has /key/list in team_member_permissions, regular
    team members must get full key visibility for that team — same as a team
    admin would. This means other members' keys AND service account keys
    (user_id=NULL) must be returned, not only the caller's own keys.

    This test pins down list_keys' classification: the team must be passed
    to _list_key_helper as a full-visibility team (admin_team_ids), not as
    a service-account-only team (member_team_ids).
    """
    member_user_id = "member-user-1"
    team_id = "team-with-permission"
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=member_user_id,
    )
    team_objects = [
        _make_member_team_table(
            team_id=team_id,
            member_user_id=member_user_id,
            member_role="user",
            team_member_permissions=["/key/list"],
        )
    ]

    helper_kwargs = await _invoke_list_keys_and_capture_helper_kwargs(
        user_api_key_dict=user_api_key_dict,
        team_objects=team_objects,
    )

    admin_team_ids = helper_kwargs.get("admin_team_ids") or []
    member_team_ids = helper_kwargs.get("member_team_ids") or []
    assert team_id in admin_team_ids, (
        "team granting /key/list permission must be classified as full-visibility "
        "(admin_team_ids), but got "
        f"admin_team_ids={admin_team_ids}, member_team_ids={member_team_ids}"
    )


@pytest.mark.asyncio
async def test_list_keys_team_member_without_key_list_permission_only_service_accounts():
    """
    Without the /key/list permission, the existing scoping must hold: the
    team is classified as member-only, so only service account keys
    (user_id=NULL) for that team are visible to the caller.
    """
    member_user_id = "member-user-2"
    team_id = "team-no-permission"
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=member_user_id,
    )
    team_objects = [
        _make_member_team_table(
            team_id=team_id,
            member_user_id=member_user_id,
            member_role="user",
            team_member_permissions=None,
        )
    ]

    helper_kwargs = await _invoke_list_keys_and_capture_helper_kwargs(
        user_api_key_dict=user_api_key_dict,
        team_objects=team_objects,
    )

    admin_team_ids = helper_kwargs.get("admin_team_ids") or []
    member_team_ids = helper_kwargs.get("member_team_ids") or []
    assert team_id not in admin_team_ids
    assert team_id in member_team_ids


@pytest.mark.asyncio
async def test_list_keys_team_member_with_permission_in_one_team_only():
    """
    Granular: a user is a member of two teams. Only one team grants
    /key/list — the other does not. The classification must respect the
    per-team permission, not leak full visibility across both teams.
    """
    member_user_id = "member-user-3"
    team_with_permission = "team-A"
    team_without_permission = "team-B"
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=member_user_id,
    )
    team_objects = [
        _make_member_team_table(
            team_id=team_with_permission,
            member_user_id=member_user_id,
            member_role="user",
            team_member_permissions=["/key/list"],
        ),
        _make_member_team_table(
            team_id=team_without_permission,
            member_user_id=member_user_id,
            member_role="user",
            team_member_permissions=[],
        ),
    ]

    helper_kwargs = await _invoke_list_keys_and_capture_helper_kwargs(
        user_api_key_dict=user_api_key_dict,
        team_objects=team_objects,
    )

    admin_team_ids = helper_kwargs.get("admin_team_ids") or []
    member_team_ids = helper_kwargs.get("member_team_ids") or []
    assert team_with_permission in admin_team_ids
    assert team_without_permission not in admin_team_ids
    assert team_without_permission in member_team_ids


@pytest.mark.asyncio
async def test_list_keys_team_admin_unaffected_by_member_permission_logic():
    """
    Sanity: a team admin's classification is unchanged by the new
    permission-aware path. They still appear in admin_team_ids (full
    visibility) regardless of the team_member_permissions value.
    """
    admin_user_id = "team-admin-user"
    team_id = "team-with-admin"
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=admin_user_id,
    )
    team_objects = [
        _make_member_team_table(
            team_id=team_id,
            member_user_id=admin_user_id,
            member_role="admin",
            team_member_permissions=None,
        )
    ]

    helper_kwargs = await _invoke_list_keys_and_capture_helper_kwargs(
        user_api_key_dict=user_api_key_dict,
        team_objects=team_objects,
    )

    admin_team_ids = helper_kwargs.get("admin_team_ids") or []
    assert team_id in admin_team_ids


def test_build_key_filter_conditions_full_visibility_team_includes_service_accounts():
    """
    Direct check on the SQL filter: when a team is in the full-visibility
    set (admin_team_ids), the filter clause for that team is
    {"team_id": {"in": [...]}} with NO user_id constraint — so service
    account keys (user_id=NULL) AND other members' keys are returned.

    This is the SQL-level proof that a member with /key/list permission
    will see service account keys for the team.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    full_visibility_team = "team-full-vis"
    where = _build_key_filter_conditions(
        user_id="member-user-x",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=[full_visibility_team],
        member_team_ids=[full_visibility_team],
        include_created_by_keys=False,
    )

    serialized = json.dumps(where)
    # Full-visibility team filter: no user_id restriction
    assert (
        json.dumps({"team_id": {"in": [full_visibility_team]}}) in serialized
    ), f"expected unrestricted team_id IN clause, got: {serialized}"
    # No service-account-only AND clause for this team (it would be redundant
    # and would erroneously narrow the visibility back to user_id=NULL).
    sa_only_clause = json.dumps(
        {"AND": [{"team_id": {"in": [full_visibility_team]}}, {"user_id": None}]}
    )
    assert (
        sa_only_clause not in serialized
    ), f"team in admin_team_ids must not also be filtered to user_id=NULL: {serialized}"


def test_build_key_filter_conditions_member_only_team_restricts_to_service_accounts():
    """
    Existing-behavior pin: when a team is ONLY in member_team_ids (not
    admin_team_ids), the filter for that team must be
    {"AND": [{"team_id": {"in": [...]}}, {"user_id": None}]} — i.e. only
    service accounts visible. This is the "no permission" baseline that
    must keep working.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    member_only_team = "team-member-only"
    where = _build_key_filter_conditions(
        user_id="member-user-y",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=[],
        member_team_ids=[member_only_team],
        include_created_by_keys=False,
    )

    serialized = json.dumps(where)
    expected = json.dumps(
        {"AND": [{"team_id": {"in": [member_only_team]}}, {"user_id": None}]}
    )
    assert (
        expected in serialized
    ), f"member-only team must be restricted to user_id=NULL keys, got: {serialized}"


def test_build_key_filter_conditions_agent_id_narrows_visibility():
    """
    Filtering /key/list by agent_id must AND the agent_id on top of the
    caller's visibility conditions (it can only narrow results, never widen
    them). Without this the UI cannot list an agent's keys server-side and
    falls back to fetching every key and filtering client-side.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    agent_id = "agent-123"
    where = _build_key_filter_conditions(
        user_id="some-user",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=["team-a"],
        member_team_ids=None,
        include_created_by_keys=False,
        agent_id=agent_id,
    )

    # agent_id must be applied as a top-level AND so it intersects (narrows) the
    # visibility OR-conditions rather than being added as another OR branch.
    assert where.get("AND"), f"expected top-level AND, got: {where}"
    assert {"agent_id": agent_id} in where["AND"], f"agent_id not ANDed: {where}"

    # Omitting agent_id must not introduce any agent_id constraint.
    where_without = _build_key_filter_conditions(
        user_id="some-user",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=["team-a"],
        member_team_ids=None,
        include_created_by_keys=False,
    )
    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_key_alias_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}"


def _search_clause(search: str, token: str) -> dict:
    return {"OR": [{"token": token}, {"key_alias": {"contains": search, "mode": "insensitive"}}]}


def test_build_key_filter_conditions_search_ors_token_and_alias_contains():
    """
    LIT-4741: `search` matches a key by its alias (case-insensitive contains) OR by
    its ID (the token column), with the pasted value used verbatim.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    hashed_where = json.loads(
        json.dumps(
            _build_key_filter_conditions(
                user_id=None,
                team_id=None,
                organization_id=None,
                key_alias=None,
                key_hash=None,
                exclude_team_id=None,
                admin_team_ids=None,
                search="already-hashed-token",
            )
        )
    )
    assert _search_clause("already-hashed-token", "already-hashed-token") in hashed_where["AND"], (
        f"hashed search not used verbatim: {hashed_where}"
    )


def test_build_key_filter_conditions_search_narrows_team_admin_visibility():
    """
    LIT-4741, same class as LIT-3243: `search` must be a top-level AND so it
    narrows a team admin's admin-team branch instead of being bypassed by it.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = json.loads(
        json.dumps(
            _build_key_filter_conditions(
                user_id="team-admin-user",
                team_id=None,
                organization_id=None,
                key_alias=None,
                key_hash=None,
                exclude_team_id=None,
                admin_team_ids=["team-a"],
                member_team_ids=["team-a"],
                include_created_by_keys=False,
                search="member-key-id",
            )
        )
    )

    assert where.get("AND"), f"expected top-level AND, got: {where}"
    assert _search_clause("member-key-id", "member-key-id") in where["AND"], f"search not ANDed: {where}"
    assert json.dumps({"team_id": {"in": ["team-a"]}}) in json.dumps(where)


@pytest.mark.asyncio
async def test_list_key_helper_applies_search_to_prisma_where():
    """LIT-4741: `search` given to _list_key_helper must reach the Prisma where clause."""
    mock_prisma_client = AsyncMock()
    mock_find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.find_many = mock_find_many
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)

    await list_key_helper(
        prisma_client=mock_prisma_client,
        page=1,
        size=50,
        user_id=None,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        search="key-id-123",
    )

    where = json.loads(json.dumps(mock_find_many.call_args.kwargs["where"]))
    assert _search_clause("key-id-123", "key-id-123") in where["AND"], f"search not in Prisma where: {where}"


_BULK_UPDATE_TOKEN: Final = "1f2e3d4c5b6a79880123456789abcdef0123456789abcdef0123456789abcdef"
_BULK_UPDATE_TEAM: Final = LiteLLM_TeamTableCachedObj(team_id="team-1")


async def _run_bulk_update_on_one_key(
    monkeypatch: pytest.MonkeyPatch,
    item_payload: Mapping[str, object],
    team: LiteLLM_TeamTableCachedObj = _BULK_UPDATE_TEAM,
    user_api_key_cache: UserApiKeyCache | None = None,
) -> tuple[BulkUpdateKeyResponse, AsyncMock]:
    from litellm.proxy.management_endpoints.key_management_endpoints import bulk_update_keys

    key_in_db = LiteLLM_VerificationToken(
        token=_BULK_UPDATE_TOKEN, user_id="test-user", team_id="team-1", max_budget=100.0, budget_id="budget-1"
    )
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=key_in_db)
    mock_prisma_client.get_data = AsyncMock(return_value=key_in_db)
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm-bulk")
    )
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {"token": _BULK_UPDATE_TOKEN}})
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)
    if user_api_key_cache is not None:
        monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", user_api_key_cache)
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", AsyncMock(return_value=team)
    )

    with (
        patch(  # test-quality-ok: the handler reads the cache and hook singletons from module globals, no injection seam
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: the permission check is a classmethod the handler calls directly, no injection seam
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: the audit hook is a classmethod the handler calls directly, no injection seam
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook",
            new_callable=AsyncMock,
        ),
    ):
        response = await bulk_update_keys(
            data=BulkUpdateKeyRequest.model_validate({"keys": [{"key": _BULK_UPDATE_TOKEN, **item_payload}]}),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin-user"
            ),
            litellm_changed_by=None,
        )

    return response, mock_prisma_client


async def _bulk_update_one_key(monkeypatch, item_payload: Mapping[str, object]) -> AsyncMock:
    response, prisma = await _run_bulk_update_on_one_key(monkeypatch, item_payload)
    assert response.failed_updates == []
    return prisma


def _written_key_row(prisma: AsyncMock) -> Mapping[str, object]:
    return prisma.update_data.call_args.kwargs["data"]


@pytest.mark.asyncio
async def test_bulk_update_keys_item_without_a_field_leaves_that_column_alone(monkeypatch):
    """A tags-only item used to reach the DB with max_budget, team_id, and budget_id as explicit
    nulls, so tagging a key wiped its budget and detached it from its team."""
    written = _written_key_row(await _bulk_update_one_key(monkeypatch, {"tags": ["team-a"]}))

    assert written["metadata"]["tags"] == ["team-a"]
    assert not {"max_budget", "team_id", "budget_id"} & written.keys()


@pytest.mark.asyncio
async def test_bulk_update_keys_explicit_null_still_clears_the_field(monkeypatch):
    """Sending `"max_budget": null` on an item is a request to remove the budget, as on /key/update."""
    written = _written_key_row(await _bulk_update_one_key(monkeypatch, {"max_budget": None}))

    assert written["max_budget"] is None
    assert not {"team_id", "budget_id"} & written.keys()


@pytest.mark.asyncio
async def test_bulk_update_keys_object_permission_is_granted_not_dropped(monkeypatch):
    """`object_permission` used to be accepted with 200 and dropped, leaving an item that carried
    nothing but the key, so the call wiped the key's budget instead of granting the permission."""
    prisma = await _bulk_update_one_key(monkeypatch, {"object_permission": {"vector_stores": ["vs-1"]}})

    upserted = prisma.db.litellm_objectpermissiontable.upsert.call_args.kwargs["data"]["create"]
    assert upserted["vector_stores"] == ["vs-1"]
    written = _written_key_row(prisma)
    assert written["object_permission_id"] == upserted["object_permission_id"]
    assert not {"max_budget", "team_id", "budget_id"} & written.keys()


@pytest.mark.asyncio
async def test_bulk_update_keys_invalidates_cache_for_new_object_permission(monkeypatch: pytest.MonkeyPatch):
    from litellm.proxy.common_utils.user_api_key_cache import object_permission_cache_key

    permission_id = str(UUID("00000000-0000-0000-0000-000000000001"))
    permission_cache_key = object_permission_cache_key(permission_id)
    user_api_key_cache = UserApiKeyCache()
    user_api_key_cache.set_cache(
        key=permission_cache_key,
        value=LiteLLM_ObjectPermissionTable(object_permission_id=permission_id, vector_stores=["stale"]),
        model_type=LiteLLM_ObjectPermissionTable,
    )
    assert (
        user_api_key_cache.get_cache(
            key=permission_cache_key,
            model_type=LiteLLM_ObjectPermissionTable,
        )
        is not None
    )
    monkeypatch.setattr(
        "litellm.proxy.management_helpers.object_permission_utils.uuid.uuid4",
        lambda: UUID(permission_id),
    )

    response, prisma = await _run_bulk_update_on_one_key(
        monkeypatch,
        {"object_permission": {"vector_stores": ["vs-1"]}},
        user_api_key_cache=user_api_key_cache,
    )

    assert response.failed_updates == []
    assert _written_key_row(prisma)["object_permission_id"] == permission_id
    assert (
        user_api_key_cache.get_cache(
            key=permission_cache_key,
            model_type=LiteLLM_ObjectPermissionTable,
        )
        is None
    )


@pytest.mark.asyncio
async def test_bulk_update_keys_object_permission_outside_the_team_allowlist_is_refused(monkeypatch):
    """A bulk item's object_permission is checked against the key's team exactly as /key/update
    checks it, so a team key cannot be granted a search tool its team does not allow."""
    team = LiteLLM_TeamTableCachedObj(
        team_id="team-1",
        object_permission=LiteLLM_ObjectPermissionTable(object_permission_id="op-team-1", search_tools=["team-search"]),
    )
    response, prisma = await _run_bulk_update_on_one_key(
        monkeypatch, {"object_permission": {"search_tools": ["other-search"]}}, team=team
    )

    assert response.successful_updates == []
    assert "not allowed by team 'team-1'" in response.failed_updates[0].failed_reason
    prisma.update_data.assert_not_called()


@pytest.mark.asyncio
async def test_generate_key_negative_max_budget():
    """
    Test that GenerateKeyRequest model allows negative max_budget values.
    Validation is done at API level, not model level.

    This prevents GET requests from breaking when they receive data with negative budgets.
    """
    # Should not raise any errors at model level
    request = GenerateKeyRequest(max_budget=-7.0)
    assert request.max_budget == -7.0


@pytest.mark.asyncio
async def test_generate_key_negative_soft_budget():
    """
    Test that GenerateKeyRequest model allows negative soft_budget values.
    Validation is done at API level, not model level.
    """
    # Should not raise any errors at model level
    request = GenerateKeyRequest(soft_budget=-10.0)
    assert request.soft_budget == -10.0


@pytest.mark.asyncio
async def test_generate_key_positive_budgets_accepted():
    """
    Test that GenerateKeyRequest accepts positive budget values.
    """
    # Should not raise any errors
    request = GenerateKeyRequest(max_budget=100.0, soft_budget=50.0)
    assert request.max_budget == 100.0
    assert request.soft_budget == 50.0


@pytest.mark.asyncio
async def test_update_key_negative_max_budget():
    """
    Test that UpdateKeyRequest model allows negative max_budget values.
    Validation is done at API level, not model level.
    """
    # Should not raise any errors at model level
    request = UpdateKeyRequest(key="test-key", max_budget=-5.0)
    assert request.max_budget == -5.0


@pytest.mark.asyncio
async def test_generate_key_with_router_settings(monkeypatch):
    """
    Test that /key/generate correctly handles router_settings by:
    1. Accepting router_settings as a dict parameter
    2. Serializing router_settings to JSON when saving to database
    3. Storing router_settings in the key record
    """
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data

    # Mock prisma_client.insert_data for both user and key tables
    async def _insert_data_side_effect(*args, **kwargs):
        table_name = kwargs.get("table_name")
        if table_name == "user":
            return MagicMock(models=[], spend=0)
        elif table_name == "key":
            return MagicMock(
                token="hashed_token_router",
                litellm_budget_table=None,
                object_permission=None,
            )
        return MagicMock()

    mock_prisma_client.insert_data = AsyncMock(side_effect=_insert_data_side_effect)
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[
        SimpleNamespace(model_id="weighted-id", model_name="gpt-4", model_info={})
    ])

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    from litellm.proxy._types import GenerateKeyRequest, LitellmUserRoles
    from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_key_fn,
    )

    # model_group_retry_policy maps a model group to a RetryPolicy, exercising
    # nested-model serialization through the key record
    router_settings_data = {
        "routing_strategy": "usage-based",
        "num_retries": 3,
        "model_group_retry_policy": {"gpt-4": {"RateLimitErrorRetries": 5}},
        "weights": {"gpt-4": {"weighted-id": 1}},
    }

    request_data = GenerateKeyRequest(
        models=["gpt-4"],
        router_settings=router_settings_data,
    )

    await generate_key_fn(
        data=request_data,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="user-router-1",
        ),
    )

    # Verify key insertion was called
    assert mock_prisma_client.insert_data.call_count >= 1
    key_insert_calls = [
        call.kwargs
        for call in mock_prisma_client.insert_data.call_args_list
        if call.kwargs.get("table_name") == "key"
    ]
    assert len(key_insert_calls) >= 1
    key_data = key_insert_calls[0]["data"]

    # Verify router_settings is present
    assert "router_settings" in key_data

    # router_settings should be present in the data passed to insert_data
    # The code uses safe_dumps to serialize router_settings, so it will be a JSON string
    router_settings_value = key_data["router_settings"]

    # Get the actual settings value for comparison
    # The code uses safe_dumps to serialize and yaml.safe_load to deserialize
    if isinstance(router_settings_value, str):
        # If it's a JSON string (from safe_dumps), deserialize it using json.loads
        # (safe_dumps produces JSON, and json.loads is the correct way to deserialize it)
        actual_settings = json.loads(router_settings_value)
    elif isinstance(router_settings_value, dict):
        # If it's still a dict, use it directly
        actual_settings = router_settings_value
    else:
        raise AssertionError(
            f"router_settings should be str or dict, got {type(router_settings_value)}"
        )

    # Verify router_settings matches input (regardless of serialization state)
    assert actual_settings == router_settings_data
    mock_prisma_client.insert_data.reset_mock()
    with pytest.raises(ProxyException, match="Unknown deployment ID"):
        await generate_key_fn(
            data=GenerateKeyRequest(router_settings={"weights": {"gpt-4": {"unknown-id": 1}}}),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="user-router-1"),
        )
    mock_prisma_client.insert_data.assert_not_awaited()


@pytest.mark.asyncio
@pytest.mark.parametrize("request_type", [UpdateKeyRequest, RegenerateKeyRequest])
@pytest.mark.parametrize("target_team", ["new-team", None])
async def test_update_key_with_router_settings(
    monkeypatch: pytest.MonkeyPatch,
    request_type: type[UpdateKeyRequest | RegenerateKeyRequest], target_team: str | None,
) -> None:
    """
    Test that /key/update correctly handles router_settings by:
    1. Accepting router_settings as a dict parameter
    2. Serializing router_settings to JSON when updating database
    3. Updating router_settings in the key record
    """
    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        prepare_key_update_data,
    )

    model = SimpleNamespace(model_id="weighted-id", model_name="gpt-4", model_info={})
    table = SimpleNamespace(find_many=AsyncMock(return_value=[model]))
    db = SimpleNamespace(db=SimpleNamespace(litellm_proxymodeltable=table))

    # Mock existing key
    existing_key = LiteLLM_VerificationToken(
        token="test-token-router",
        key_alias="test-key",
        models=["gpt-3.5-turbo"],
        user_id="test-user",
        team_id=None,
        auto_rotate=False,
        rotation_interval=None,
        metadata={},
    )

    # Test updating router_settings
    router_settings_data = {
        "routing_strategy": "latency-based",
        "num_retries": 2,
        "weights": {"gpt-4": {"weighted-id": 1}},
    }

    update_request = request_type(
        key="test-token-router", router_settings=router_settings_data
    )

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key,
        prisma_client=db, llm_router=None,
    )

    # Verify router_settings is serialized to JSON string
    assert "router_settings" in result
    assert isinstance(result["router_settings"], str)

    # Verify router_settings can be deserialized and matches input
    deserialized_settings = json.loads(result["router_settings"])
    assert deserialized_settings == router_settings_data

    with pytest.raises(HTTPException, match="Unknown deployment ID"):
        await prepare_key_update_data(
            request_type(key=existing_key.token, router_settings={"weights": {"gpt-4": {"unknown-id": 1}}}),
            existing_key,
            prisma_client=db, llm_router=None,
        )
    existing_key.team_id = "old-team"
    existing_key.router_settings = router_settings_data
    move = request_type(key=existing_key.token, team_id=target_team)
    retained = await prepare_key_update_data(move, existing_key, prisma_client=db, llm_router=None)
    assert retained["team_id"] == target_team
    assert "router_settings" not in retained
    model.model_info = {"team_id": "old-team"}
    with pytest.raises(HTTPException, match="Unknown deployment ID"):
        await prepare_key_update_data(move, existing_key, prisma_client=db, llm_router=None)
    cleared = await prepare_key_update_data(
        request_type(key=existing_key.token, team_id=target_team, router_settings={}), existing_key,
        prisma_client=db, llm_router=None,
    )
    assert cleared["team_id"] == target_team
    assert json.loads(cleared["router_settings"]) == {}


@pytest.mark.asyncio
async def test_validate_max_budget():
    """
    Test _validate_max_budget helper function.

    Tests:
    1. Positive max_budget should pass
    2. Zero max_budget should pass
    3. Negative max_budget should raise HTTPException
    4. None max_budget should pass
    """
    from fastapi import HTTPException

    # Test Case 1: Positive max_budget should pass
    try:
        _validate_max_budget(100.0)
        _validate_max_budget(0.0)
    except HTTPException:
        pytest.fail("_validate_max_budget raised HTTPException for valid values")

    # Test Case 2: None max_budget should pass
    try:
        _validate_max_budget(None)
    except HTTPException:
        pytest.fail("_validate_max_budget raised HTTPException for None")

    # Test Case 3: Negative max_budget should raise HTTPException
    with pytest.raises(HTTPException) as exc_info:
        _validate_max_budget(-10.0)

    assert exc_info.value.status_code == 400
    assert "max_budget must be a non-negative finite number" in str(
        exc_info.value.detail
    )
    assert "negative" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_get_and_validate_existing_key():
    """
    Test _get_and_validate_existing_key helper function.

    Tests:
    1. Successfully retrieve existing key
    2. Key not found raises ProxyException
    3. Database not connected raises HTTPException
    """
    from fastapi import HTTPException

    from litellm.proxy._types import ProxyException

    # Test Case 1: Successfully retrieve existing key
    mock_prisma_client = AsyncMock()
    mock_key = LiteLLM_VerificationToken(
        token="test-key-123",
        user_id="user-123",
        models=["gpt-4"],
        team_id=None,
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
        return_value="hashed-test-key-123",
    ):
        result = await _get_and_validate_existing_key(
            token="test-key-123",
            prisma_client=mock_prisma_client,
        )

    assert result == mock_key
    mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once_with(
        where={"token": "hashed-test-key-123"}, include={"object_permission": True}
    )

    # Test Case 2: Key not found raises ProxyException
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
        return_value="hashed-non-existent-key",
    ):
        with pytest.raises(ProxyException) as exc_info:
            await _get_and_validate_existing_key(
                token="non-existent-key",
                prisma_client=mock_prisma_client,
            )

    assert str(exc_info.value.code) == "404"
    assert "Key not found" in exc_info.value.message

    # Test Case 3: Database not connected raises HTTPException
    with pytest.raises(HTTPException) as exc_info:
        await _get_and_validate_existing_key(
            token="test-key-123",
            prisma_client=None,
        )

    assert exc_info.value.status_code == 500
    assert "Database not connected" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_process_single_key_update():
    """
    Test _process_single_key_update helper function.

    Tests successful key update with all validations passing.
    """
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateKeyRequestItem,
    )

    # Setup mocks
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()
    mock_llm_router = MagicMock()

    # Mock existing key
    existing_key = LiteLLM_VerificationToken(
        token="test-key-123",
        user_id="user-123",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
        tags=None,
    )

    # Mock updated key response
    updated_key_data = {
        "user_id": "user-123",
        "models": ["gpt-4"],
        "team_id": None,
        "max_budget": 100.0,
        "tags": ["production"],
    }

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=existing_key
    )
    mock_updated_key_obj = MagicMock()
    mock_updated_key_obj.model_dump.return_value = updated_key_data
    mock_prisma_client.update_data = AsyncMock(
        return_value={"data": mock_updated_key_obj}
    )

    # Mock prepare_key_update_data
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.prepare_key_update_data"
    ) as mock_prepare:
        mock_prepare.return_value = {"max_budget": 100.0, "tags": ["production"]}

        # Mock TeamMemberPermissionChecks
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint"
        ) as mock_permission_check:
            mock_permission_check.return_value = None

            # Mock _delete_cache_key_object
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
            ) as mock_delete_cache:
                mock_delete_cache.return_value = None

                # Mock hash_token (imported from litellm.proxy._types)
                with patch("litellm.types.proxy.auth.user_api_key_auth.hash_token") as mock_hash:
                    mock_hash.return_value = "hashed-test-key-123"

                    # Mock _hash_token_if_needed
                    with patch(
                        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
                        return_value="hashed-test-key-123",
                    ):
                        # Mock KeyManagementEventHooks
                        with patch(
                            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook"
                        ):
                            # Create update request
                            update_key_request = UpdateKeyRequest(
                                key="test-key-123",
                                max_budget=100.0,
                                tags=["production"],
                            )

                            user_api_key_dict = UserAPIKeyAuth(
                                user_role=LitellmUserRoles.PROXY_ADMIN,
                                api_key="sk-admin",
                                user_id="admin-user",
                            )

                            # Call the function
                            result = await _process_single_key_update(
                                update_key_request=update_key_request,
                                user_api_key_dict=user_api_key_dict,
                                litellm_changed_by=None,
                                prisma_client=mock_prisma_client,
                                user_api_key_cache=mock_user_api_key_cache,
                                proxy_logging_obj=mock_proxy_logging_obj,
                                llm_router=mock_llm_router,
                            )

                            # Verify results
                            assert result is not None
                            assert "token" not in result  # Token should be removed
                            assert result.get("max_budget") == 100.0
                            assert result.get("tags") == ["production"]

                            # Verify mocks were called
                            mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once()
                            mock_prisma_client.update_data.assert_called_once()
                            mock_delete_cache.assert_called_once()


@pytest.mark.asyncio
async def test_bulk_update_keys_success(monkeypatch):
    """
    Test /key/bulk_update endpoint with successful updates.

    Tests:
    1. Multiple keys updated successfully
    2. Response contains correct counts and data
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_keys,
    )
    from litellm.proxy.proxy_server import (
        llm_router,
        prisma_client,
        proxy_logging_obj,
        user_api_key_cache,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateKeyRequest,
        BulkUpdateKeyRequestItem,
    )

    # Setup mocks
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()
    mock_llm_router = MagicMock()

    # Mock existing keys
    existing_key_1 = LiteLLM_VerificationToken(
        token="test-key-1",
        user_id="user-123",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
    )
    existing_key_2 = LiteLLM_VerificationToken(
        token="test-key-2",
        user_id="user-123",
        models=["gpt-3.5-turbo"],
        team_id=None,
        max_budget=50.0,
    )

    # Mock updated key responses
    updated_key_1_data = {
        "user_id": "user-123",
        "models": ["gpt-4"],
        "max_budget": 100.0,
        "tags": ["production"],
    }
    updated_key_2_data = {
        "user_id": "user-123",
        "models": ["gpt-3.5-turbo"],
        "max_budget": 200.0,
        "tags": ["staging"],
    }

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        side_effect=[existing_key_1, existing_key_2]
    )
    mock_updated_key_1_obj = MagicMock()
    mock_updated_key_1_obj.model_dump.return_value = updated_key_1_data
    mock_updated_key_2_obj = MagicMock()
    mock_updated_key_2_obj.model_dump.return_value = updated_key_2_data
    mock_prisma_client.update_data = AsyncMock(
        side_effect=[
            {"data": mock_updated_key_1_obj},
            {"data": mock_updated_key_2_obj},
        ]
    )

    # Patch dependencies
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", mock_llm_router)

    # Mock helper functions
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.prepare_key_update_data"
    ) as mock_prepare:
        mock_prepare.side_effect = [
            {"max_budget": 100.0, "tags": ["production"]},
            {"max_budget": 200.0, "tags": ["staging"]},
        ]

        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint"
        ):
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
            ):
                with patch("litellm.types.proxy.auth.user_api_key_auth.hash_token") as mock_hash:
                    mock_hash.side_effect = ["hashed-key-1", "hashed-key-2"]

                    def _hash_for_bulk_success(token: str) -> str:
                        return {
                            "test-key-1": "hashed-key-1",
                            "test-key-2": "hashed-key-2",
                        }[token]

                    with patch(
                        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
                        side_effect=_hash_for_bulk_success,
                    ):
                        with patch(
                            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook"
                        ):
                            # Create request
                            request_data = BulkUpdateKeyRequest(
                                keys=[
                                    BulkUpdateKeyRequestItem(
                                        key="test-key-1",
                                        max_budget=100.0,
                                        tags=["production"],
                                    ),
                                    BulkUpdateKeyRequestItem(
                                        key="test-key-2",
                                        max_budget=200.0,
                                        tags=["staging"],
                                    ),
                                ]
                            )

                            user_api_key_dict = UserAPIKeyAuth(
                                user_role=LitellmUserRoles.PROXY_ADMIN,
                                api_key="sk-admin",
                                user_id="admin-user",
                            )

                            # Call endpoint
                            response = await bulk_update_keys(
                                data=request_data,
                                user_api_key_dict=user_api_key_dict,
                                litellm_changed_by=None,
                            )

                            # Verify response
                            assert response.total_requested == 2
                            assert len(response.successful_updates) == 2
                            assert len(response.failed_updates) == 0
                            assert response.successful_updates[0].key == "test-key-1"
                            assert response.successful_updates[1].key == "test-key-2"


@pytest.mark.asyncio
async def test_bulk_update_keys_partial_failures(monkeypatch):
    """
    Test /key/bulk_update endpoint with partial failures.

    Tests:
    1. Some keys update successfully, others fail
    2. Response contains both successful and failed updates
    3. Failed updates include error messages
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_keys,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateKeyRequest,
        BulkUpdateKeyRequestItem,
    )

    # Setup mocks
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()
    mock_llm_router = MagicMock()

    # Mock existing keys
    existing_key_1 = LiteLLM_VerificationToken(
        token="test-key-1",
        user_id="user-123",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
    )

    # Mock updated key response for successful update
    updated_key_1_data = {
        "user_id": "user-123",
        "models": ["gpt-4"],
        "max_budget": 100.0,
        "tags": ["production"],
    }

    # First key exists, second key doesn't exist
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        side_effect=[existing_key_1, None]  # Second key not found
    )
    mock_updated_key_1_obj = MagicMock()
    mock_updated_key_1_obj.model_dump.return_value = updated_key_1_data
    mock_prisma_client.update_data = AsyncMock(
        return_value={"data": mock_updated_key_1_obj}
    )
    # Mock get_data for the error handler path (used to fetch key_info on failure)
    mock_prisma_client.get_data = AsyncMock(return_value=None)

    # Patch dependencies
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", mock_llm_router)

    # Mock helper functions
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.prepare_key_update_data"
    ) as mock_prepare:
        mock_prepare.return_value = {"max_budget": 100.0, "tags": ["production"]}

        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint"
        ):
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
            ):
                with patch("litellm.types.proxy.auth.user_api_key_auth.hash_token") as mock_hash:
                    mock_hash.return_value = "hashed-key-1"

                    def _hash_for_bulk_partial(token: str) -> str:
                        return {
                            "test-key-1": "hashed-key-1",
                            "non-existent-key": "hashed-non-existent-key",
                        }[token]

                    with patch(
                        "litellm.proxy.management_endpoints.key_management_endpoints.hash_token_if_needed",
                        side_effect=_hash_for_bulk_partial,
                    ):
                        with patch(
                            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook"
                        ):
                            # Create request with one valid and one invalid key
                            request_data = BulkUpdateKeyRequest(
                                keys=[
                                    BulkUpdateKeyRequestItem(
                                        key="test-key-1",
                                        max_budget=100.0,
                                        tags=["production"],
                                    ),
                                    BulkUpdateKeyRequestItem(
                                        key="non-existent-key",
                                        max_budget=200.0,
                                        tags=["staging"],
                                    ),
                                ]
                            )

                            user_api_key_dict = UserAPIKeyAuth(
                                user_role=LitellmUserRoles.PROXY_ADMIN,
                                api_key="sk-admin",
                                user_id="admin-user",
                            )

                            # Call endpoint
                            response = await bulk_update_keys(
                                data=request_data,
                                user_api_key_dict=user_api_key_dict,
                                litellm_changed_by=None,
                            )

                            # Verify response
                            assert response.total_requested == 2
                            assert len(response.successful_updates) == 1
                            assert len(response.failed_updates) == 1
                            assert response.successful_updates[0].key == "test-key-1"
                            assert response.failed_updates[0].key == "non-existent-key"
                            assert (
                                "Key not found"
                                in response.failed_updates[0].failed_reason
                            )


@pytest.mark.parametrize(
    "reset_to,key_spend,key_max_budget,budget_max_budget,expected_error",
    [
        ("not_a_number", 100.0, None, None, "reset_to must be a float"),
        (None, 100.0, None, None, "reset_to must be a float"),
        ([], 100.0, None, None, "reset_to must be a float"),
        ({}, 100.0, None, None, "reset_to must be a float"),
        (-1.0, 100.0, None, None, "reset_to must be >= 0"),
        (-0.1, 100.0, None, None, "reset_to must be >= 0"),
        (101.0, 100.0, None, None, "reset_to (101.0) must be <= current spend (100.0)"),
        (150.0, 100.0, None, None, "reset_to (150.0) must be <= current spend (100.0)"),
        (50.0, 100.0, 30.0, None, "reset_to (50.0) must be <= budget (30.0)"),
    ],
)
def test_validate_reset_spend_value_invalid(
    reset_to, key_spend, key_max_budget, budget_max_budget, expected_error
):
    key_in_db = LiteLLM_VerificationToken(
        token="test-token",
        user_id="test-user",
        spend=key_spend,
        max_budget=key_max_budget,
        litellm_budget_table=(
            LiteLLM_BudgetTable(
                budget_id="test-budget", max_budget=budget_max_budget
            ).dict()
            if budget_max_budget is not None
            else None
        ),
    )

    with pytest.raises(HTTPException) as exc_info:
        _validate_reset_spend_value(reset_to, key_in_db)

    assert exc_info.value.status_code == 400
    assert expected_error in str(exc_info.value.detail)


@pytest.mark.parametrize(
    "reset_to,key_spend,key_max_budget,budget_max_budget",
    [
        (0.0, 100.0, None, None),
        (0, 100.0, None, None),
        (50.0, 100.0, None, None),
        (100.0, 100.0, None, None),
        (25.0, 100.0, 50.0, None),
        (0.0, 0.0, None, None),
        (10.5, 50.0, 20.0, None),
    ],
)
def test_validate_reset_spend_value_valid(
    reset_to, key_spend, key_max_budget, budget_max_budget
):
    key_in_db = LiteLLM_VerificationToken(
        token="test-token",
        user_id="test-user",
        spend=key_spend,
        max_budget=key_max_budget,
        litellm_budget_table=(
            LiteLLM_BudgetTable(
                budget_id="test-budget", max_budget=budget_max_budget
            ).dict()
            if budget_max_budget is not None
            else None
        ),
    )

    result = _validate_reset_spend_value(reset_to, key_in_db)
    assert result == float(reset_to)


def test_validate_reset_spend_value_no_budget_table():
    key_in_db = LiteLLM_VerificationToken(
        token="test-token",
        user_id="test-user",
        spend=100.0,
        max_budget=50.0,
        litellm_budget_table=None,
    )

    result = _validate_reset_spend_value(25.0, key_in_db)
    assert result == 25.0


def test_validate_reset_spend_value_none_spend():
    key_in_db = LiteLLM_VerificationToken(
        token="test-token",
        user_id="test-user",
        spend=0.0,
        max_budget=None,
        litellm_budget_table=None,
    )

    result = _validate_reset_spend_value(0.0, key_in_db)
    assert result == 0.0

    with pytest.raises(HTTPException) as exc_info:
        _validate_reset_spend_value(1.0, key_in_db)
    assert exc_info.value.status_code == 400
    assert "must be <= current spend" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_reset_key_spend_success(monkeypatch):
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "hashed-test-key"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=100.0,
        max_budget=200.0,
        litellm_budget_table=None,
    )

    updated_key = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=50.0,
        max_budget=200.0,
        budget_reset_at=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=updated_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )

    with (
        patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_proxy_or_team_admin_for_key"
        ) as mock_check_admin,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
        ) as mock_delete_cache,
    ):
        mock_hash_token.return_value = hashed_key
        mock_check_admin.return_value = None
        mock_delete_cache.return_value = None

        # Mock spend_counter_cache to verify direct cache set instead of
        # _invalidate_spend_counter (removed in favour of atomic cache write).
        mock_spend_counter_cache = MagicMock()
        mock_spend_counter_cache.redis_cache = None
        monkeypatch.setattr(
            "litellm.proxy.proxy_server.spend_counter_cache",
            mock_spend_counter_cache,
        )

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        response = await reset_key_spend_fn(
            key="sk-test-key",
            data=ResetSpendRequest(reset_to=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

        assert response["spend"] == 50.0
        assert response["previous_spend"] == 100.0
        assert response["key_hash"] == hashed_key
        assert response["max_budget"] == 200.0
        mock_prisma_client.db.litellm_verificationtoken.update.assert_called_once()
        mock_delete_cache.assert_awaited_once()
        mock_spend_counter_cache.in_memory_cache.set_cache.assert_any_call(
            key=f"spend:key:{hashed_key}", value=50.0, ttl=60
        )
        # spend_db_floor marker is also set to the reset value (LIT-3803 pattern),
        # so a request landing on a pod with a warm pre-reset floor marker cannot
        # re-derive and re-apply the stale spend.
        mock_spend_counter_cache.in_memory_cache.set_cache.assert_any_call(
            key=f"spend_db_floor:spend:key:{hashed_key}", value=50.0, ttl=5
        )


@pytest.mark.asyncio
async def test_reset_key_spend_resets_budget_windows(monkeypatch):
    """
    Regression test: a key with an extra time-windowed budget (`budget_limits`,
    e.g. a daily cap layered on top of the lifetime max_budget) must have that
    window's own Redis counter reset too, and its `reset_at` advanced, not just
    the lifetime spend/counter.

    Before the fix, reset_key_spend_fn only reset spend:key:{hash}, leaving
    spend:key:{hash}:window:{duration} at its pre-reset value. Since
    get_current_spend always re-derives a window counter from real
    LiteLLM_SpendLogs rows inside the still-open window, merely zeroing that
    counter without also advancing reset_at is not durable either: the very
    next request would re-sum the unchanged historical spend and put the
    counter right back above the window's max_budget, so
    _virtual_key_multi_budget_check kept raising BudgetExceededError (422) on
    every request even though the key's own reported spend read $0.
    """
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "hashed-window-budget-key"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=80.0,
        max_budget=1000.0,
        litellm_budget_table=None,
        budget_limits=[
            {
                "budget_duration": "1d",
                "max_budget": 50.0,
                "reset_at": "2020-01-01T00:00:00+00:00",
            }
        ],
    )
    updated_key = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=0.0,
        max_budget=1000.0,
        budget_reset_at=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=updated_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )

    mock_spend_counter_cache = MagicMock()
    mock_spend_counter_cache.redis_cache = MagicMock()
    mock_spend_counter_cache.redis_cache.async_set_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.spend_counter_cache",
        mock_spend_counter_cache,
    )

    with (
        patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token,  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
        patch(  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
            "litellm.proxy.management_endpoints.key_management_endpoints._check_proxy_or_team_admin_for_key"
        ) as mock_check_admin,
        patch(  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
        ) as mock_delete_cache,
    ):
        mock_hash_token.return_value = hashed_key
        mock_check_admin.return_value = None
        mock_delete_cache.return_value = None

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        before_call = datetime.now(timezone.utc)
        response = await reset_key_spend_fn(
            key="sk-test-key",
            data=ResetSpendRequest(reset_to=0.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        after_call = datetime.now(timezone.utc)

    assert response["spend"] == 0.0

    window_counter_key = f"spend:key:{hashed_key}:window:1d"
    mock_spend_counter_cache.in_memory_cache.set_cache.assert_any_call(
        key=window_counter_key, value=0.0, ttl=60
    )
    mock_spend_counter_cache.redis_cache.async_set_cache.assert_any_call(
        key=window_counter_key, value=0.0, ttl=60
    )
    mock_spend_counter_cache.in_memory_cache.set_cache.assert_any_call(
        key=f"spend_db_floor:{window_counter_key}", value=0.0, ttl=5
    )

    # The window's DB row must be advanced past the historical spend that
    # triggered the block, or the next authoritative-floor recompute re-sums
    # the still-open window's spend logs and silently re-inflates the counter.
    # reset_at must land at (roughly) now + 1 day: get_budget_window_start
    # derives window_start as reset_at - budget_duration, so this is what
    # makes window_start land at "now" and exclude the historical spend that
    # triggered the block. The next *calendar-aligned* midnight (what a naive
    # get_budget_reset_time("1d") call would give) is the wrong value here --
    # it would put window_start at the start of the day already in progress,
    # which still covers that spend.
    assert mock_prisma_client.db.litellm_verificationtoken.update.call_count == 2
    window_update_call = mock_prisma_client.db.litellm_verificationtoken.update.call_args_list[1]
    assert window_update_call.kwargs["where"] == {"token": hashed_key}
    persisted_windows = json.loads(window_update_call.kwargs["data"]["budget_limits"])
    assert len(persisted_windows) == 1
    assert persisted_windows[0]["budget_duration"] == "1d"
    assert persisted_windows[0]["max_budget"] == 50.0
    persisted_reset_at = datetime.fromisoformat(persisted_windows[0]["reset_at"])
    assert before_call + timedelta(days=1) <= persisted_reset_at <= after_call + timedelta(days=1)


@pytest.mark.asyncio
async def test_reset_key_spend_no_budget_limits_skips_window_reset(monkeypatch):
    """A key with no budget_limits must not trigger any extra DB write beyond
    the lifetime spend update; _reset_key_budget_windows should be a no-op."""
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "hashed-no-window-key"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=100.0,
        max_budget=200.0,
        litellm_budget_table=None,
        budget_limits=None,
    )
    updated_key = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=0.0,
        max_budget=200.0,
        budget_reset_at=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=updated_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )

    mock_spend_counter_cache = MagicMock()
    mock_spend_counter_cache.redis_cache = None
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.spend_counter_cache",
        mock_spend_counter_cache,
    )

    with (
        patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token,  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
        patch(  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
            "litellm.proxy.management_endpoints.key_management_endpoints._check_proxy_or_team_admin_for_key"
        ) as mock_check_admin,
        patch(  # test-quality-ok: no HTTP boundary; same pattern as test_reset_key_spend_success
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
        ) as mock_delete_cache,
    ):
        mock_hash_token.return_value = hashed_key
        mock_check_admin.return_value = None
        mock_delete_cache.return_value = None

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        response = await reset_key_spend_fn(
            key="sk-test-key",
            data=ResetSpendRequest(reset_to=0.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert response["spend"] == 0.0
    mock_prisma_client.db.litellm_verificationtoken.update.assert_called_once()


@pytest.mark.asyncio
async def test_delete_cache_key_object_broadcasts_invalidation(monkeypatch):
    """
    Regression test (LIT-3803 pattern applied to keys): evicting a key's
    cached auth object must broadcast the invalidation to every other worker,
    or a worker that already cached the pre-mutation object (e.g. pre-reset
    spend) keeps serving it until its own local TTL expires, even though this
    worker's own cache and the DB have already moved on.
    """
    real_user_api_key_cache = UserApiKeyCache()
    await real_user_api_key_cache.async_set_cache(
        key="hashed-broadcast-key",
        value=UserAPIKeyAuth(api_key="sk-broadcast", spend=100.0),
        model_type=UserAPIKeyAuth,
    )
    mock_proxy_logging_obj = MagicMock()
    mock_proxy_logging_obj.internal_usage_cache.dual_cache.async_delete_cache = AsyncMock()

    with patch(  # test-quality-ok: pub/sub broadcast to other workers has no HTTP boundary to fake
        "litellm.proxy.auth.auth_checks.publish_auth_cache_invalidation"
    ) as mock_publish:
        mock_publish.return_value = None
        await delete_cache_key_object(
            hashed_token="hashed-broadcast-key",
            user_api_key_cache=real_user_api_key_cache,
            proxy_logging_obj=mock_proxy_logging_obj,
        )

    # Real, observable state: the cache object itself no longer holds the entry.
    assert real_user_api_key_cache.get_cache(key="hashed-broadcast-key") is None
    mock_publish.assert_awaited_once_with(cache_key="hashed-broadcast-key")


@pytest.mark.asyncio
async def test_update_key_spend_updates_counter(monkeypatch):
    """
    Test that updating a key's spend via update_key_fn immediately updates the spend counter.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = AsyncMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=10.0,
        max_budget=200.0,
        litellm_budget_table=None,
    )

    mock_prisma_client.get_data = AsyncMock(return_value=key_in_db)
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {"spend": 0.0}})
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)
    mock_spend_counter_cache = MagicMock()
    mock_spend_counter_cache.redis_cache = MagicMock()
    mock_spend_counter_cache.redis_cache.async_set_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.spend_counter_cache",
        mock_spend_counter_cache,
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
    ) as mock_delete_cache:
        mock_delete_cache.return_value = None

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        mock_request = MagicMock()
        mock_request.query_params = {}

        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key="sk-test-key", spend=0.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

        mock_delete_cache.assert_awaited_once()
        mock_spend_counter_cache.in_memory_cache.set_cache.assert_called_once_with(
            key=f"spend:key:{hashed_key}", value=0.0, ttl=60
        )
        mock_spend_counter_cache.redis_cache.async_set_cache.assert_awaited_once_with(
            key=f"spend:key:{hashed_key}", value=0.0, ttl=60
        )


@pytest.mark.asyncio
async def test_reset_key_spend_success_team_admin(monkeypatch):
    """Test that team admin can reset key spend for keys in their team."""
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "hashed-test-key"
    team_id = "test-team-123"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        team_id=team_id,
        spend=100.0,
        max_budget=200.0,
        litellm_budget_table=None,
    )

    updated_key = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        team_id=team_id,
        spend=50.0,
        max_budget=200.0,
        budget_reset_at=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=updated_key
    )

    # Set up team table with user as admin
    team_table = LiteLLM_TeamTableCachedObj(
        team_id=team_id,
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="team-admin-user", role="admin"),
            Member(user_id="test-user", role="user"),
        ],
    )

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    with (
        patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
        ) as mock_delete_cache,
    ):
        mock_hash_token.return_value = hashed_key
        mock_delete_cache.return_value = None

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-team-admin",
            user_id="team-admin-user",
        )

        response = await reset_key_spend_fn(
            key="sk-test-key",
            data=ResetSpendRequest(reset_to=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

        assert response["spend"] == 50.0
        assert response["previous_spend"] == 100.0
        assert response["key_hash"] == hashed_key
        assert response["max_budget"] == 200.0
        mock_prisma_client.db.litellm_verificationtoken.update.assert_called_once()
        mock_delete_cache.assert_awaited_once()


@pytest.mark.asyncio
async def test_reset_key_spend_key_not_found(monkeypatch):
    mock_prisma_client = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    with patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token:
        mock_hash_token.return_value = "hashed-key"

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        with pytest.raises(HTTPException) as exc_info:
            await reset_key_spend_fn(
                key="sk-test-key",
                data=ResetSpendRequest(reset_to=50.0),
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )

        assert exc_info.value.status_code == 404
        assert "Key not found" in str(
            exc_info.value.detail
        ) or "Key sk-test-key not found" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_reset_key_spend_db_not_connected(monkeypatch):
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin-user",
    )

    with pytest.raises(HTTPException) as exc_info:
        await reset_key_spend_fn(
            key="sk-test-key",
            data=ResetSpendRequest(reset_to=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc_info.value.status_code == 500
    assert "DB not connected" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_reset_key_spend_validation_error(monkeypatch):
    mock_prisma_client = MagicMock()
    key_in_db = LiteLLM_VerificationToken(
        token="hashed-key",
        user_id="test-user",
        spend=100.0,
        max_budget=None,
        litellm_budget_table=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    with patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token:
        mock_hash_token.return_value = "hashed-key"

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        with pytest.raises(HTTPException) as exc_info:
            await reset_key_spend_fn(
                key="sk-test-key",
                data=ResetSpendRequest(reset_to=150.0),
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )

        assert exc_info.value.status_code == 400
        assert "must be <= current spend" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_reset_key_spend_authorization_failure(monkeypatch):
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()

    hashed_key = "hashed-test-key"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        team_id="team-1",
        spend=100.0,
        max_budget=None,
        litellm_budget_table=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )

    with (
        patch("litellm.proxy.proxy_server.hash_token") as mock_hash_token,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_proxy_or_team_admin_for_key"
        ) as mock_check_admin,
    ):
        mock_hash_token.return_value = hashed_key
        mock_check_admin.side_effect = HTTPException(
            status_code=403, detail={"error": "Not authorized"}
        )

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-user",
            user_id="user-1",
        )

        with pytest.raises(HTTPException) as exc_info:
            await reset_key_spend_fn(
                key="sk-test-key",
                data=ResetSpendRequest(reset_to=50.0),
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )

        assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_reset_key_spend_hashed_key(monkeypatch):
    mock_prisma_client = MagicMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    hashed_key = "already-hashed-key"
    key_in_db = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=100.0,
        max_budget=None,
        litellm_budget_table=None,
    )

    updated_key = LiteLLM_VerificationToken(
        token=hashed_key,
        user_id="test-user",
        spend=50.0,
        max_budget=None,
        budget_reset_at=None,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=updated_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_proxy_or_team_admin_for_key"
        ) as mock_check_admin,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object"
        ) as mock_delete_cache,
    ):
        mock_check_admin.return_value = None
        mock_delete_cache.return_value = None

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        response = await reset_key_spend_fn(
            key=hashed_key,
            data=ResetSpendRequest(reset_to=50.0),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

        assert response["spend"] == 50.0
        mock_prisma_client.db.litellm_verificationtoken.find_unique.assert_called_once_with(
            where={"token": hashed_key}, include={"litellm_budget_table": True}
        )


@pytest.mark.asyncio
async def test_validate_key_list_check_proxy_admin():
    mock_prisma_client = AsyncMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-user",
    )

    result = await validate_key_list_check(
        user_api_key_dict=user_api_key_dict,
        user_id=None,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        prisma_client=mock_prisma_client,
    )

    assert result is None


@pytest.mark.asyncio
async def test_validate_key_list_check_team_admin_success():
    mock_prisma_client = AsyncMock()
    user_info = LiteLLM_UserTable(
        user_id="test-user",
        user_email="[email protected]",
        teams=["team-1"],
        organization_memberships=[],
    )

    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=user_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    result = await validate_key_list_check(
        user_api_key_dict=user_api_key_dict,
        user_id=None,
        team_id="team-1",
        organization_id=None,
        key_alias=None,
        key_hash=None,
        prisma_client=mock_prisma_client,
    )

    assert result is not None
    assert result.user_id == "test-user"


@pytest.mark.asyncio
async def test_validate_key_list_check_team_admin_fail():
    mock_prisma_client = AsyncMock()
    user_info = LiteLLM_UserTable(
        user_id="test-user",
        user_email="[email protected]",
        teams=["team-1"],
        organization_memberships=[],
    )

    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=user_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    with pytest.raises(ProxyException) as exc_info:
        await validate_key_list_check(
            user_api_key_dict=user_api_key_dict,
            user_id=None,
            team_id="team-2",
            organization_id=None,
            key_alias=None,
            key_hash=None,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.code == "403" or exc_info.value.code == 403
    assert "not authorized to check this team's keys" in exc_info.value.message


@pytest.mark.asyncio
async def test_validate_key_list_check_key_hash_authorized():
    mock_prisma_client = AsyncMock()
    user_info = LiteLLM_UserTable(
        user_id="test-user",
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )

    key_info = LiteLLM_VerificationToken(
        token="hashed-key",
        user_id="test-user",
    )

    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=user_info
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints._can_user_query_key_info"
    ) as mock_can_query:
        mock_can_query.return_value = True

        result = await validate_key_list_check(
            user_api_key_dict=user_api_key_dict,
            user_id=None,
            team_id=None,
            organization_id=None,
            key_alias=None,
            key_hash="hashed-key",
            prisma_client=mock_prisma_client,
        )

        assert result is not None
        assert result.user_id == "test-user"


@pytest.mark.asyncio
async def test_validate_key_list_check_key_hash_unauthorized():
    mock_prisma_client = AsyncMock()
    user_info = LiteLLM_UserTable(
        user_id="test-user",
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )

    key_info = LiteLLM_VerificationToken(
        token="hashed-key",
        user_id="other-user",
    )

    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=user_info
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints._can_user_query_key_info"
    ) as mock_can_query:
        mock_can_query.return_value = False

        with pytest.raises(HTTPException) as exc_info:
            await validate_key_list_check(
                user_api_key_dict=user_api_key_dict,
                user_id=None,
                team_id=None,
                organization_id=None,
                key_alias=None,
                key_hash="hashed-key",
                prisma_client=mock_prisma_client,
            )

        assert exc_info.value.status_code == 403
        assert "not allowed to access this key's info" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_validate_key_list_check_key_hash_not_found():
    mock_prisma_client = AsyncMock()
    user_info = LiteLLM_UserTable(
        user_id="test-user",
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )

    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=user_info
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        side_effect=Exception("Key not found")
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    with pytest.raises(ProxyException) as exc_info:
        await validate_key_list_check(
            user_api_key_dict=user_api_key_dict,
            user_id=None,
            team_id=None,
            organization_id=None,
            key_alias=None,
            key_hash="non-existent-key",
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.code == "403" or exc_info.value.code == 403
    assert "Key Hash not found" in exc_info.value.message


@pytest.mark.asyncio
async def test_validate_key_list_check_key_hash_row_missing():
    """A key_hash with no row reaches the same 'Key Hash not found' 403 as a failed
    lookup, instead of blowing up inside the ownership check on a None row."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(
            user_id="test-user",
            user_email="[email protected]",
            teams=[],
            organization_memberships=[],
        )
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
        api_key="sk-caller",
    )

    with pytest.raises(ProxyException) as exc_info:
        await validate_key_list_check(
            user_api_key_dict=user_api_key_dict,
            user_id=None,
            team_id=None,
            organization_id=None,
            key_alias=None,
            key_hash="hash-of-a-deleted-key",
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.code == "403" or exc_info.value.code == 403
    assert exc_info.value.param == "key_hash"
    assert "Key Hash not found" in exc_info.value.message


@pytest.mark.asyncio
async def test_validate_key_list_check_proxy_admin_viewer_skips_db_lookup():
    """proxy_admin_viewer takes the same unscoped read fast-path as proxy_admin, so no
    user row is fetched and none of the user/team scoping filters apply."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(
            user_id="viewer-user",
            user_email="[email protected]",
            teams=[],
            organization_memberships=[],
        )
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
        user_id="viewer-user",
    )

    result = await validate_key_list_check(
        user_api_key_dict=user_api_key_dict,
        user_id="someone-else",
        team_id="team-viewer-is-not-in",
        organization_id=None,
        key_alias=None,
        key_hash=None,
        prisma_client=mock_prisma_client,
    )

    assert result is None
    mock_prisma_client.db.litellm_usertable.find_unique.assert_not_awaited()
    assert mock_prisma_client.mock_calls == []


@pytest.mark.asyncio
async def test_validate_key_list_check_internal_user_cannot_query_other_user():
    """Admin-view parity must not leak past the admin roles: an internal user still
    cannot list another user's keys."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(
            user_id="test-user",
            user_email="[email protected]",
            teams=[],
            organization_memberships=[],
        )
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="test-user",
    )

    with pytest.raises(ProxyException) as exc_info:
        await validate_key_list_check(
            user_api_key_dict=user_api_key_dict,
            user_id="other-user",
            team_id=None,
            organization_id=None,
            key_alias=None,
            key_hash=None,
            prisma_client=mock_prisma_client,
        )

    assert exc_info.value.code == "403"
    assert "not authorized to check another user's keys" in exc_info.value.message


@pytest.mark.asyncio
async def test_key_with_budget_id_does_not_store_budget_duration():
    """
    Test that when a key is created with budget_id but without explicit
    budget_duration, the key does NOT get budget_duration stored on it.

    Keys with budget_id follow their linked budget tier's reset schedule;
    reset_budget_for_litellm_budget_table() resets them when the tier resets.
    This avoids duplicating budget_duration on keys so tier updates apply
    automatically to all linked keys.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    mock_prisma = MagicMock()

    mock_generate_key = AsyncMock(
        return_value={
            "key": "sk-test-key",
            "expires": None,
            "user_id": "test-user",
            "team_id": None,
        }
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            mock_generate_key,
        ),
    ):
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                budget_id="7d-budget-tier",
                max_budget=10.0,
                # NOTE: budget_duration is intentionally NOT set here
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-9876",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    mock_generate_key.assert_awaited_once()
    call_kwargs = mock_generate_key.call_args.kwargs

    # Key should NOT have key_budget_duration - it follows the budget tier's schedule
    assert call_kwargs.get("key_budget_duration") is None, (
        "key_budget_duration should be None for budget-linked keys without explicit "
        f"budget_duration; got: {call_kwargs.get('key_budget_duration')}"
    )

    # No budget tier lookup - we don't copy budget_duration onto the key
    mock_prisma.db.litellm_budgettable.find_unique.assert_not_called()


@pytest.mark.asyncio
async def test_key_does_not_override_explicit_budget_duration():
    """
    Test that when a key is created with both budget_id and an explicit
    budget_duration, the explicit budget_duration takes precedence over
    the budget tier's budget_duration.
    """
    from unittest.mock import AsyncMock, MagicMock, patch

    mock_prisma = MagicMock()
    # The budget tier has budget_duration="7d"
    mock_budget_row = MagicMock()
    mock_budget_row.budget_duration = "7d"
    mock_prisma.db.litellm_budgettable.find_unique = AsyncMock(
        return_value=mock_budget_row
    )

    mock_generate_key = AsyncMock(
        return_value={
            "key": "sk-test-key",
            "expires": None,
            "user_id": "test-user",
            "team_id": None,
        }
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            mock_generate_key,
        ),
    ):
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                budget_id="7d-budget-tier",
                max_budget=10.0,
                budget_duration="30d",  # explicit budget_duration should take precedence
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-9876",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    mock_generate_key.assert_awaited_once()
    call_kwargs = mock_generate_key.call_args.kwargs

    # The explicit budget_duration should take precedence
    assert call_kwargs.get("key_budget_duration") == "30d", (
        "Explicit budget_duration should take precedence over the budget tier's value "
        f"but got: {call_kwargs.get('key_budget_duration')}"
    )

    # The budget tier should NOT have been looked up since budget_duration was explicit
    mock_prisma.db.litellm_budgettable.find_unique.assert_not_called()


@pytest.mark.asyncio
@patch(
    "litellm.proxy.management_endpoints.key_management_endpoints.rotate_mcp_server_credentials_master_key"
)
async def test_rotate_master_key_reencrypts_model_params_in_place(
    mock_rotate_mcp,
):
    """
    Regression test for: master key rotation wipes every non-credential column
    on LiteLLM_ProxyModelTable. Rotation used to rebuild the table via
    delete_many + create_many from Deployment objects, which carry no
    blocked/created_at/created_by/updated_at/updated_by, so every rotation
    reset blocked to False (silently unblocking blocked models) and rewrote the
    audit columns. Rotation must instead update only litellm_params (the sole
    encrypted column) on each existing row, keyed by model_id.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        rotate_master_key,
    )

    # Setup mock prisma client
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db = MagicMock()

    # Mock model table — return one model
    mock_model = MagicMock()
    mock_model.model_id = "model-1"
    mock_model.model_name = "test-model"
    mock_model.litellm_params = (
        '{"model": "openai/gpt-4", "api_key": "sk-encrypted-old"}'
    )
    mock_model.model_info = '{"id": "model-1"}'
    mock_model.created_by = "admin"
    mock_model.updated_by = "admin"
    mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(
        return_value=[mock_model]
    )

    # Mock transaction context manager
    mock_tx = AsyncMock()
    mock_tx.litellm_proxymodeltable = MagicMock()
    mock_tx.litellm_proxymodeltable.delete_many = AsyncMock()
    mock_tx.litellm_proxymodeltable.create_many = AsyncMock()
    mock_tx.litellm_proxymodeltable.update_many = AsyncMock()
    mock_prisma_client.db.tx = MagicMock(
        return_value=AsyncMock(
            __aenter__=AsyncMock(return_value=mock_tx),
            __aexit__=AsyncMock(return_value=False),
        )
    )

    # Mock config table — no env vars
    mock_prisma_client.db.litellm_config.find_many = AsyncMock(return_value=[])

    # Mock credentials table — no credentials
    mock_prisma_client.db.litellm_credentialstable.find_many = AsyncMock(
        return_value=[]
    )

    # Mock MCP rotation
    mock_rotate_mcp.return_value = None

    # Mock proxy_config
    mock_proxy_config = MagicMock()
    mock_proxy_config.decrypt_model_list_from_db.return_value = [
        {
            "model_name": "test-model",
            "litellm_params": {
                "model": "openai/gpt-4",
                "api_key": "sk-decrypted-key",
            },
            "model_info": {"id": "model-1"},
        }
    ]

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-9876",
        user_id="test-user",
    )

    with patch(
        "litellm.proxy.proxy_server.proxy_config",
        mock_proxy_config,
    ):
        await rotate_master_key(
            prisma_client=mock_prisma_client,
            user_api_key_dict=user_api_key_dict,
            current_master_key="sk-old-master-key",
            new_master_key="sk-new-master-key",
        )

    # Rotation must never rewrite whole rows: no delete + recreate
    mock_tx.litellm_proxymodeltable.delete_many.assert_not_called()
    mock_tx.litellm_proxymodeltable.create_many.assert_not_called()

    mock_tx.litellm_proxymodeltable.update_many.assert_called_once()
    call_args = mock_tx.litellm_proxymodeltable.update_many.call_args

    assert call_args.kwargs["where"] == {
        "model_id": "model-1"
    }, "the re-encrypted params must land on the same row, keyed by model_id"

    update_data = call_args.kwargs["data"]
    assert set(update_data.keys()) == {"litellm_params"}, (
        "rotation must touch only the encrypted litellm_params column; writing any "
        f"other column wipes it (blocked, audit columns), got {sorted(update_data.keys())}"
    )

    import prisma

    assert isinstance(
        update_data["litellm_params"], prisma.Json
    ), f"litellm_params should be prisma.Json for update_many(), got {type(update_data['litellm_params'])}"
    reencrypted_params = update_data["litellm_params"].data
    assert set(reencrypted_params.keys()) >= {"model", "api_key"}
    assert (
        reencrypted_params["api_key"] != "sk-decrypted-key"
    ), "api_key must be stored re-encrypted under the new master key, not in plaintext"


@pytest.mark.asyncio
async def test_rotate_master_key_keeps_environment_variables_it_cannot_decrypt(monkeypatch):
    from types import SimpleNamespace
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_if_encrypted_with, encrypt_value_helper
    from litellm.proxy.management_endpoints.key_management_endpoints import rotate_master_key
    from litellm.proxy.proxy_server import ProxyConfig

    monkeypatch.setenv("LITELLM_SALT_KEY", "sk-old-master-key")
    under_another_key = encrypt_value_helper("stored-under-another-key", new_encryption_key="sk-another-master-key")
    for key in ("ROTATION_TEST_ENCRYPTED", "ROTATION_TEST_PLAINTEXT", "ROTATION_TEST_UNDER_ANOTHER_KEY"):
        monkeypatch.setenv(key, "restored-by-monkeypatch")
        monkeypatch.delenv(key)
    prisma_client = AsyncMock()
    prisma_client.db = MagicMock()
    prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
    prisma_client.db.litellm_config.update = AsyncMock()
    prisma_client.writer_db.litellm_config.find_many = AsyncMock(
        return_value=[
            SimpleNamespace(
                param_name="environment_variables",
                param_value={
                    "ROTATION_TEST_ENCRYPTED": encrypt_value_helper("stored-encrypted"),
                    "ROTATION_TEST_PLAINTEXT": "stored-plaintext",
                    "ROTATION_TEST_UNDER_ANOTHER_KEY": under_another_key,
                },
            )
        ]
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", ProxyConfig())

    await rotate_master_key(
        prisma_client=prisma_client,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876"),
        current_master_key="sk-old-master-key",
        new_master_key="sk-new-master-key",
    )

    stored = prisma_client.db.litellm_config.update.call_args.kwargs["data"]["param_value"].data
    rotated = decrypt_if_encrypted_with(stored["ROTATION_TEST_ENCRYPTED"], "sk-new-master-key")
    assert {**stored, "ROTATION_TEST_ENCRYPTED": rotated} == {
        "ROTATION_TEST_ENCRYPTED": "stored-encrypted",
        "ROTATION_TEST_PLAINTEXT": "stored-plaintext",
        "ROTATION_TEST_UNDER_ANOTHER_KEY": under_another_key,
    }


@pytest.mark.asyncio
async def test_rotate_master_key_keeps_an_environment_variable_the_read_replica_has_not_caught_up_on(monkeypatch):
    from types import SimpleNamespace
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_if_encrypted_with, encrypt_value_helper
    from litellm.proxy.management_endpoints.key_management_endpoints import rotate_master_key
    from litellm.proxy.proxy_server import ProxyConfig

    monkeypatch.setenv("LITELLM_SALT_KEY", "sk-old-master-key")
    monkeypatch.setenv("ROTATION_TEST_SAVED_A_MOMENT_AGO", "restored-by-monkeypatch")
    monkeypatch.delenv("ROTATION_TEST_SAVED_A_MOMENT_AGO")

    def rows(values: dict[str, str]) -> list[SimpleNamespace]:
        return [SimpleNamespace(param_name="environment_variables", param_value=values)]

    prisma_client = AsyncMock()
    prisma_client.db = MagicMock()
    prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
    prisma_client.db.litellm_config.update = AsyncMock()
    prisma_client.db.litellm_config.find_many = AsyncMock(return_value=rows({}))
    prisma_client.writer_db.litellm_config.find_many = AsyncMock(
        return_value=rows({"ROTATION_TEST_SAVED_A_MOMENT_AGO": encrypt_value_helper("saved-a-moment-ago")})
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_config", ProxyConfig())

    await rotate_master_key(
        prisma_client=prisma_client,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-9876"),
        current_master_key="sk-old-master-key",
        new_master_key="sk-new-master-key",
    )

    stored = prisma_client.db.litellm_config.update.call_args.kwargs["data"]["param_value"].data
    assert {key: decrypt_if_encrypted_with(value, "sk-new-master-key") for key, value in stored.items()} == {
        "ROTATION_TEST_SAVED_A_MOMENT_AGO": "saved-a-moment-ago"
    }


async def test_default_key_generate_params_duration(monkeypatch):
    """
    Test that default_key_generate_params with 'duration' is applied
    when no duration is provided in the key generation request.

    Regression test for bug where 'duration' was missing from the list
    of fields populated from default_key_generate_params.
    """
    import litellm

    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Set default_key_generate_params with duration
    monkeypatch.setattr(litellm, "default_key_generate_params", {"duration": "180d"})

    request = GenerateKeyRequest()  # No duration specified
    response = await _common_key_generation_helper(
        data=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="1234",
        ),
        litellm_changed_by=None,
        team_table=None,
    )

    # Verify duration was applied from defaults
    assert request.duration == "180d"


async def test_default_key_generate_params_object_permission_applied_when_absent(
    monkeypatch,
):
    """
    default_key_generate_params.object_permission is applied to a key that
    doesn't specify object_permission at all.
    """
    import litellm

    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm-1")
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {
                "object_permission": {"vector_stores": ["default-vs"]}
            },
    )

    request = GenerateKeyRequest()  # No object_permission specified
    await _common_key_generation_helper(
        data=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="1234",
        ),
        litellm_changed_by=None,
        team_table=None,
    )

    created_data = mock_prisma_client.db.litellm_objectpermissiontable.create.call_args.kwargs["data"]
    assert created_data["vector_stores"] == ["default-vs"]


async def test_default_key_generate_params_object_permission_merges_partial(
    monkeypatch,
):
    """
    default_key_generate_params.object_permission fills only the fields the
    caller left unset - an explicitly supplied field (agents here) is
    preserved alongside the defaulted field (vector_stores).
    """
    import litellm
    from litellm.proxy._types import LiteLLM_ObjectPermissionBase

    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm-2")
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {
                "object_permission": {"vector_stores": ["default-vs"]}
            },
    )

    request = GenerateKeyRequest(
        object_permission=LiteLLM_ObjectPermissionBase(agents=["agent-1"])
    )
    await _common_key_generation_helper(
        data=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="1234",
        ),
        litellm_changed_by=None,
        team_table=None,
    )

    created_data = mock_prisma_client.db.litellm_objectpermissiontable.create.call_args.kwargs["data"]
    assert created_data["agents"] == ["agent-1"]
    assert created_data["vector_stores"] == ["default-vs"]


async def test_default_key_generate_params_object_permission_does_not_override_explicit(
    monkeypatch,
):
    """
    A field the caller explicitly set on object_permission must win over the
    same field in default_key_generate_params.
    """
    import litellm
    from litellm.proxy._types import LiteLLM_ObjectPermissionBase

    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm-3")
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {
                "object_permission": {"vector_stores": ["default-vs"]}
            },
    )

    request = GenerateKeyRequest(
        object_permission=LiteLLM_ObjectPermissionBase(
            vector_stores=["explicit-vs"]
        )
    )
    await _common_key_generation_helper(
        data=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="1234",
        ),
        litellm_changed_by=None,
        team_table=None,
    )

    created_data = mock_prisma_client.db.litellm_objectpermissiontable.create.call_args.kwargs["data"]
    assert created_data["vector_stores"] == ["explicit-vs"]


async def test_default_key_generate_params_object_permission_not_rejected_for_non_admin_personal_key(
    monkeypatch,
):
    """
    Regression test: a default_key_generate_params.object_permission containing
    a team-scoped field (vector_stores) must not turn ordinary non-admin
    personal key creation into a 403. The default is merged in *after* the
    caller-scope validation, so it is never mistaken for a caller-requested
    permission.
    """
    import litellm

    mock_prisma_client = AsyncMock()
    mock_insert_data = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.insert_data = mock_insert_data
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=None
    )
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(
            token="hashed_token_123", litellm_budget_table=None, object_permission=None
        )
    )
    mock_prisma_client.db.litellm_objectpermissiontable = MagicMock()
    mock_prisma_client.db.litellm_objectpermissiontable.create = AsyncMock(
        return_value=MagicMock(object_permission_id="objperm-4")
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {
                "object_permission": {"vector_stores": ["default-vs"]}
            },
    )

    request = GenerateKeyRequest(user_id="alice")  # No object_permission specified
    response = await _common_key_generation_helper(
        data=request,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-alice",
            user_id="alice",
        ),
        litellm_changed_by=None,
        team_table=None,
    )

    assert response is not None
    created_data = mock_prisma_client.db.litellm_objectpermissiontable.create.call_args.kwargs["data"]
    assert created_data["vector_stores"] == ["default-vs"]


@pytest.mark.asyncio
async def test_build_key_filter_member_team_service_accounts():
    """
    Test that regular team members can see service accounts (user_id=NULL)
    for their teams, but NOT other members' personal keys.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "regular-member-123"
    member_team_ids = ["team-A", "team-B"]

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=member_team_ids,
        include_created_by_keys=False,
    )

    # Should have AND with OR conditions
    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Should have 2 conditions: user's own keys + member team service accounts
    assert len(or_conditions) == 2

    # First: user's own keys (exact match — non-admin callers use exact matching)
    user_cond = or_conditions[0]
    assert user_cond["user_id"] == user_id

    # Second: service accounts for member teams (user_id=None AND team_id in member teams)
    service_account_cond = or_conditions[1]
    assert "AND" in service_account_cond
    and_parts = service_account_cond["AND"]
    assert {"team_id": {"in": member_team_ids}} in and_parts
    assert {"user_id": None} in and_parts


@pytest.mark.asyncio
async def test_build_key_filter_admin_sees_all_team_keys():
    """
    Test that team admins see ALL keys for their teams (not just service accounts),
    and that member_team_ids doesn't duplicate admin teams.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "admin-user-123"
    admin_team_ids = ["team-A"]
    member_team_ids = ["team-A", "team-B"]

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=admin_team_ids,
        member_team_ids=member_team_ids,
        include_created_by_keys=False,
    )

    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Should have 3 conditions:
    # 1. user's own keys
    # 2. admin team keys (all keys for team-A)
    # 3. member-only service accounts (only service accounts for team-B, since team-A is already covered by admin)
    assert len(or_conditions) == 3

    # Find admin condition
    admin_cond = None
    service_account_cond = None
    for cond in or_conditions:
        if isinstance(cond.get("team_id"), dict) and "in" in cond.get("team_id", {}):
            admin_cond = cond
        elif "AND" in cond:
            service_account_cond = cond

    assert admin_cond is not None, "Admin team condition should be present"
    assert admin_cond["team_id"]["in"] == admin_team_ids

    # member-only condition should only include team-B (team-A is covered by admin)
    assert (
        service_account_cond is not None
    ), "Service account condition should be present"
    and_parts = service_account_cond["AND"]
    assert {"team_id": {"in": ["team-B"]}} in and_parts
    assert {"user_id": None} in and_parts


@pytest.mark.asyncio
async def test_build_key_filter_created_by_scoped_to_current_teams():
    """
    Test that created_by filter is scoped to teams user currently belongs to.
    A former team member should NOT see service accounts they created for
    a team they've left.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-456"
    # User is currently only a member of team-A (left team-B)
    member_team_ids = ["team-A"]

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=member_team_ids,
        include_created_by_keys=True,
    )

    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Find the created_by condition
    created_by_cond = None
    for cond in or_conditions:
        if "AND" in cond:
            and_parts = cond["AND"]
            for part in and_parts:
                if isinstance(part, dict) and "created_by" in part:
                    created_by_cond = cond
                    break

    assert created_by_cond is not None, "Created by condition should be present"

    # created_by should be scoped: created_by=user AND (team_id in [team-A] OR team_id=None)
    and_parts = created_by_cond["AND"]
    assert {"created_by": user_id} in and_parts

    # Find the OR part that scopes to current teams
    team_scope = None
    for part in and_parts:
        if isinstance(part, dict) and "OR" in part:
            team_scope = part["OR"]

    assert team_scope is not None, "Team scope OR condition should be present"
    assert {"team_id": {"in": member_team_ids}} in team_scope
    assert {"team_id": None} in team_scope


@pytest.mark.asyncio
async def test_build_key_filter_created_by_no_teams():
    """
    Test that when user has no team memberships (empty list), created_by
    only returns non-team keys (personal keys).
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-no-teams"
    member_team_ids = []  # User has no team memberships

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=member_team_ids,
        include_created_by_keys=True,
    )

    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Find the created_by condition
    created_by_cond = None
    for cond in or_conditions:
        if "AND" in cond:
            and_parts = cond["AND"]
            for part in and_parts:
                if isinstance(part, dict) and "created_by" in part:
                    created_by_cond = cond
                    break

    assert created_by_cond is not None
    and_parts = created_by_cond["AND"]
    assert {"created_by": user_id} in and_parts
    assert {"team_id": None} in and_parts
    # Should NOT have an OR with team_id in [] - just a simple team_id=None
    for part in and_parts:
        if isinstance(part, dict) and "OR" in part:
            pytest.fail("Should not have OR condition when member_team_ids is empty")


@pytest.mark.asyncio
async def test_build_key_filter_backward_compat_no_member_team_ids():
    """
    Test backward compatibility: when member_team_ids is None (not provided),
    created_by filter should use the old unrestricted behavior.
    This ensures direct callers of _list_key_helper (like Prometheus) still work.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-789"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,  # Not provided
        include_created_by_keys=True,
    )

    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Find the created_by condition - should be simple {"created_by": user_id}
    created_by_cond = None
    for cond in or_conditions:
        if "created_by" in cond:
            created_by_cond = cond

    assert created_by_cond is not None
    assert created_by_cond == {"created_by": user_id}
    assert len(created_by_cond) == 1, "Should be simple created_by without team scoping"


@pytest.mark.asyncio
async def test_build_key_filter_admin_all_member_overlap():
    """
    Test that when user is admin of ALL teams they belong to,
    no member-only service account condition is added (would be redundant).
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "admin-all"
    admin_team_ids = ["team-A", "team-B"]
    member_team_ids = ["team-A", "team-B"]

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=admin_team_ids,
        member_team_ids=member_team_ids,
        include_created_by_keys=False,
    )

    assert "AND" in where
    or_conditions = where["AND"][1]["OR"]

    # Should only have 2 conditions: user's own keys + admin team keys
    # No member-only service account condition since all teams are admin
    assert len(or_conditions) == 2

    # Verify no AND condition with user_id=None exists (that's the member-only pattern)
    for cond in or_conditions:
        if "AND" in cond:
            and_parts = cond["AND"]
            if {"user_id": None} in and_parts:
                pytest.fail(
                    "Should not have member-only service account condition "
                    "when user is admin of all teams"
                )


@pytest.mark.asyncio
async def test_build_key_filter_project_id():
    """
    Test that project_id is applied as a global AND condition, narrowing all results
    to keys that belong to the specified project.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-123"
    project_id = "proj-abc"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
        project_id=project_id,
    )

    # Should be wrapped in a top-level AND for the project_id filter
    assert "AND" in where
    and_parts = where["AND"]
    assert len(and_parts) == 2

    # Second part of AND should be the project_id filter
    assert {"project_id": project_id} in and_parts


@pytest.mark.asyncio
async def test_build_key_filter_access_group_id():
    """
    Test that access_group_id is applied as a global AND condition using hasSome,
    narrowing results to keys whose access_group_ids array contains the given ID.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-123"
    access_group_id = "ag-xyz"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
        access_group_id=access_group_id,
    )

    # Should be wrapped in a top-level AND for the access_group_id filter
    assert "AND" in where
    and_parts = where["AND"]
    assert len(and_parts) == 2

    # Second part of AND should use hasSome for the array field
    assert {"access_group_ids": {"hasSome": [access_group_id]}} in and_parts


@pytest.mark.asyncio
async def test_build_key_filter_project_id_and_access_group_id():
    """
    Test that project_id and access_group_id stack correctly when both are provided.
    Both should be applied as AND conditions, narrowing results to keys that match both.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-123"
    project_id = "proj-abc"
    access_group_id = "ag-xyz"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
        project_id=project_id,
        access_group_id=access_group_id,
    )

    assert "AND" in where
    outer_and = where["AND"]
    assert {"project_id": project_id} in outer_and
    assert {"access_group_ids": {"hasSome": [access_group_id]}} in outer_and


@pytest.mark.asyncio
async def test_build_key_filter_team_id_scoped():
    """
    When team_id is provided, it should act as a global AND filter so keys
    from other teams are excluded — even when the user is admin of multiple teams.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = _build_key_filter_conditions(
        user_id="multi-team-user",
        team_id="team-A",
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=["team-A", "team-B"],
        member_team_ids=["team-A", "team-B"],
        include_created_by_keys=True,
    )

    # The team_id filter must be a direct child of the outermost AND,
    # not buried inside an OR branch (which was the bug).
    assert "AND" in where, f"Expected top-level AND, got: {where}"
    outer_and = where["AND"]
    assert {
        "team_id": "team-A"
    } in outer_and, (
        f"Expected {{'team_id': 'team-A'}} as a direct AND condition, got: {outer_and}"
    )


@pytest.mark.asyncio
async def test_build_key_filter_admin_substring_matching():
    """
    Admin callers get substring (contains + insensitive) matching for user_id
    and key_alias when both substring flags are set.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "alice"
    key_alias = "prod"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=key_alias,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
        use_substring_matching=True,
        use_key_alias_substring_matching=True,
    )

    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
async def test_build_key_filter_non_admin_exact_matching():
    """
    Non-admin callers get exact matching for user_id and key_alias when
    use_substring_matching=False (the default).  This prevents a user whose
    ID is a substring of another user's ID from seeing that user's keys.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "[email protected]"
    key_alias = "my-key"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=key_alias,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
        use_substring_matching=False,
    )

    # Exact match — no contains/insensitive wrapping
    assert where["AND"][0]["user_id"] == user_id
    assert {"key_alias": key_alias} in where["AND"]


@pytest.mark.asyncio
async def test_build_key_filter_default_is_exact_matching():
    """
    The default for use_substring_matching is False, ensuring backward
    compatibility — callers that don't pass the flag get exact matching.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    user_id = "user-123"

    where = _build_key_filter_conditions(
        user_id=user_id,
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        member_team_ids=None,
        include_created_by_keys=False,
    )

    # Single OR condition is flattened into the top-level where dict
    assert where["user_id"] == user_id


@pytest.mark.asyncio
async def test_get_member_team_ids():
    """
    Test that get_member_team_ids returns all teams where user is a member
    (any role), not just admin teams.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        get_member_team_ids,
    )

    user_id = "member-user-123"

    # Create mock user info with teams
    user_info = LiteLLM_UserTable(
        user_id=user_id,
        teams=["team-A", "team-B", "team-C"],
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-test",
        user_id=user_id,
    )

    # Mock prisma client
    mock_prisma_client = AsyncMock()

    # Create mock team objects - user is admin of team-A, member of team-B, not in team-C's members list
    mock_team_a = MagicMock()
    mock_team_a.model_dump.return_value = {
        "team_id": "team-A",
        "team_alias": "Team A",
        "members_with_roles": [
            {"user_id": user_id, "role": "admin", "user_email": None}
        ],
        "max_budget": None,
        "budget_duration": None,
        "budget_reset_at": None,
        "tpm_limit": None,
        "rpm_limit": None,
        "models": [],
        "blocked": False,
    }

    mock_team_b = MagicMock()
    mock_team_b.model_dump.return_value = {
        "team_id": "team-B",
        "team_alias": "Team B",
        "members_with_roles": [
            {"user_id": user_id, "role": "user", "user_email": None}
        ],
        "max_budget": None,
        "budget_duration": None,
        "budget_reset_at": None,
        "tpm_limit": None,
        "rpm_limit": None,
        "models": [],
        "blocked": False,
    }

    mock_team_c = MagicMock()
    mock_team_c.model_dump.return_value = {
        "team_id": "team-C",
        "team_alias": "Team C",
        "members_with_roles": [
            {"user_id": "other-user", "role": "admin", "user_email": None}
        ],
        "max_budget": None,
        "budget_duration": None,
        "budget_reset_at": None,
        "tpm_limit": None,
        "rpm_limit": None,
        "models": [],
        "blocked": False,
    }

    mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(
        return_value=[mock_team_a, mock_team_b, mock_team_c]
    )

    result = await get_member_team_ids(
        complete_user_info=user_info,
        user_api_key_dict=user_api_key_dict,
        prisma_client=mock_prisma_client,
    )

    # Should return team-A and team-B (user is a member of both)
    # Should NOT return team-C (user is not in members list)
    assert sorted(result) == ["team-A", "team-B"]


@pytest.mark.asyncio
async def test_generate_key_with_agent_id():
    """Test that agent_id is accepted in GenerateKeyRequest and passed to generate_key_helper_fn."""
    from litellm.proxy._types import GenerateKeyRequest

    # Verify GenerateKeyRequest accepts agent_id
    request = GenerateKeyRequest(
        key_alias="agent-test-key",
        agent_id="test-agent-123",
        models=[],
    )
    assert request.agent_id == "test-agent-123"
    data_json = request.model_dump(exclude_unset=True, exclude_none=True)
    assert data_json["agent_id"] == "test-agent-123"


@pytest.mark.asyncio
async def test_generate_key_helper_fn_agent_id():
    """Test that generate_key_helper_fn passes agent_id into the insert_data call."""
    from unittest.mock import AsyncMock, MagicMock, call, patch

    import litellm.proxy.management_endpoints.key_management_endpoints as km

    mock_prisma_client = AsyncMock()
    mock_insert = AsyncMock(
        return_value=MagicMock(
            token="sk-test",
            created_at=None,
            updated_at=None,
            litellm_budget_table=None,
        )
    )
    mock_prisma_client.insert_data = mock_insert

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        await generate_key_helper_fn(
            request_type="key",
            agent_id="test-agent-456",
            key_alias="test-agent-key",
            models=[],
            table_name="key",
        )

    assert mock_insert.called, "insert_data was never called"
    # insert_data is called as insert_data(data=key_data, ...)
    call_kwargs = mock_insert.call_args.kwargs
    key_data = call_kwargs.get("data", {})
    assert (
        key_data.get("agent_id") == "test-agent-456"
    ), f"Expected agent_id='test-agent-456' in key_data, got: {key_data.get('agent_id')}"


def _make_admin_key_dict() -> UserAPIKeyAuth:
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN.value,
        user_id="admin-user",
    )


@pytest.mark.asyncio
async def test_key_aliases_response_shape():
    """Test that key_aliases returns the correct paginated response shape."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 2}],
            [{"key_alias": "alias-alpha"}, {"key_alias": "alias-beta"}],
        ]
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        result = await key_aliases(
            user_api_key_dict=_make_admin_key_dict(),
            page=1,
            size=50,
            search=None,
        )

    assert result["aliases"] == ["alias-alpha", "alias-beta"]
    assert result["total_count"] == 2
    assert result["current_page"] == 1
    assert result["total_pages"] == 1
    assert result["size"] == 50

    # Both SQL calls must filter out null/empty aliases
    count_sql = mock_prisma_client.db.query_raw.call_args_list[0].args[0]
    aliases_sql = mock_prisma_client.db.query_raw.call_args_list[1].args[0]
    assert "key_alias IS NOT NULL" in count_sql
    assert "key_alias IS NOT NULL" in aliases_sql


@pytest.mark.asyncio
async def test_key_aliases_pagination_skip_take():
    """Test that LIMIT and OFFSET are correctly derived from page and size."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 120}],
            [],
        ]
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        result = await key_aliases(
            user_api_key_dict=_make_admin_key_dict(),
            page=3,
            size=25,
            search=None,
        )

    assert result["current_page"] == 3
    assert result["size"] == 25
    assert result["total_count"] == 120
    assert result["total_pages"] == 5  # ceil(120 / 25)

    # aliases query params: [UI_SESSION_TOKEN_TEAM_ID, size=25, offset=50]
    aliases_call_args = mock_prisma_client.db.query_raw.call_args_list[1].args
    assert aliases_call_args[-2] == 25  # LIMIT = size
    assert aliases_call_args[-1] == 50  # OFFSET = (3 - 1) * 25


@pytest.mark.asyncio
async def test_key_aliases_search_filter():
    """Test that the search param adds a case-insensitive ILIKE condition."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 0}],
            [],
        ]
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        await key_aliases(
            user_api_key_dict=_make_admin_key_dict(),
            page=1,
            size=50,
            search="my-key",
        )

    count_call = mock_prisma_client.db.query_raw.call_args_list[0]
    count_sql = count_call.args[0]
    count_params = count_call.args[1:]

    assert "ILIKE" in count_sql
    assert "%my-key%" in count_params


@pytest.mark.asyncio
async def test_key_aliases_no_search_omits_ilike_filter():
    """Test that without a search term no ILIKE condition is added."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 0}],
            [],
        ]
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        await key_aliases(
            user_api_key_dict=_make_admin_key_dict(),
            page=1,
            size=50,
            search=None,
        )

    count_sql = mock_prisma_client.db.query_raw.call_args_list[0].args[0]
    assert "ILIKE" not in count_sql


@pytest.mark.asyncio
async def test_key_aliases_internal_user_scoped_to_own_keys_and_teams():
    """Test that internal users only see aliases for their own keys and team keys."""
    mock_prisma_client = AsyncMock()

    # Mock user table lookup to return teams
    mock_user_row = MagicMock()
    mock_user_row.teams = ["team-abc", "team-xyz"]
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=mock_user_row
    )

    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 1}],
            [{"key_alias": "my-alias"}],
        ]
    )

    internal_user = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER.value,
        user_id="user-123",
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        result = await key_aliases(
            user_api_key_dict=internal_user,
            page=1,
            size=50,
            search=None,
        )

    assert result["aliases"] == ["my-alias"]

    # Verify the SQL includes user_id and team_id scoping
    count_sql = mock_prisma_client.db.query_raw.call_args_list[0].args[0]
    assert "user_id = " in count_sql
    assert "team_id IN " in count_sql

    # Verify the params include user_id and team IDs
    count_params = mock_prisma_client.db.query_raw.call_args_list[0].args[1:]
    assert "user-123" in count_params
    assert "team-abc" in count_params
    assert "team-xyz" in count_params


@pytest.mark.asyncio
async def test_key_aliases_admin_sees_all():
    """Test that proxy admins see all aliases without user/team scoping."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=[
            [{"count": 3}],
            [
                {"key_alias": "alias-a"},
                {"key_alias": "alias-b"},
                {"key_alias": "alias-c"},
            ],
        ]
    )

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        result = await key_aliases(
            user_api_key_dict=_make_admin_key_dict(),
            page=1,
            size=50,
            search=None,
        )

    assert len(result["aliases"]) == 3

    # Admin queries should NOT have user_id or team_id scoping
    count_sql = mock_prisma_client.db.query_raw.call_args_list[0].args[0]
    assert "user_id = " not in count_sql
    assert "team_id IN " not in count_sql


class TestValidateKeyAliasFormat:
    @pytest.fixture(autouse=True)
    def reset_key_alias_flag(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(litellm, "enable_key_alias_format_validation", False)

    @pytest.fixture(autouse=True)
    def reset_key_alias_pattern(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(litellm, "key_alias_pattern", None)

    def test_validation_skipped_when_flag_disabled(self):
        """When enable_key_alias_format_validation is False (default), no charset/length validation occurs."""
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        # Even invalid aliases should pass silently when the flag is off
        _validate_key_alias_format(None)
        _validate_key_alias_format("")
        _validate_key_alias_format("!invalid!")
        _validate_key_alias_format("a" * 256)

    @pytest.mark.parametrize(
        "unsafe_alias",
        [
            "../../../other-app/creds",
            "litellm/../../secret",
            "foo\n- !grant\n  role: !!admin\n  member: attacker",
            "foo\rbar",
            "foo\x00bar",
            "my-test-key\t",
        ],
    )
    def test_validate_key_alias_format_rejects_traversal_and_control_chars_even_when_flag_disabled(
        self, unsafe_alias
    ):
        """
        Regression test: this check must reject an invalid key_alias unconditionally,
        even when enable_key_alias_format_validation (the separate, opt-in charset
        rule) is disabled.
        """
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        with pytest.raises(ProxyException) as exc:
            _validate_key_alias_format(unsafe_alias)
        assert str(exc.value.code) == "400"
        assert "Invalid key_alias" in str(exc.value.message)
        assert "control characters" in str(exc.value.message)
        assert '".." path segment' in str(exc.value.message)

    def test_validate_key_alias_format_valid(self, monkeypatch):
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "enable_key_alias_format_validation", True)
        # Valid cases
        _validate_key_alias_format(None)  # OK
        _validate_key_alias_format("valid-alias")
        _validate_key_alias_format("valid_alias")
        _validate_key_alias_format("valid.alias")
        _validate_key_alias_format("valid/alias")
        _validate_key_alias_format("a" * 255)
        _validate_key_alias_format("my-key-123")
        _validate_key_alias_format("user/[email protected]")
        _validate_key_alias_format("team/[email protected]")

    def test_validate_key_alias_format_invalid(self, monkeypatch):
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )
        from litellm.proxy._types import ProxyException

        monkeypatch.setattr(litellm, "enable_key_alias_format_validation", True)
        invalid_aliases = [
            "",  # empty
            " ",  # whitespace
            "a",  # too short (min 2)
            "!",  # special char
            "-start",  # non-alphanumeric start
            "end-",  # non-alphanumeric end
            "invalid#char",  # invalid char
            "a" * 256,  # too long
            "  leading",
            "trailing  ",
        ]

        for alias in invalid_aliases:
            with pytest.raises(ProxyException) as exc:
                _validate_key_alias_format(alias)
            assert str(exc.value.code) == "400"
            assert "Invalid key_alias format" in str(exc.value.message)

    def test_configured_pattern_applies_with_flag_off(self, monkeypatch: pytest.MonkeyPatch) -> None:
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "key_alias_pattern", r"^[a-z0-9]+(-[a-z0-9]+)*$")
        with pytest.raises(ProxyException) as exc:
            _validate_key_alias_format("Prod Key")
        assert str(exc.value.code) == "400"
        assert exc.value.param == "key_alias"
        assert "key_alias_pattern" in str(exc.value.message)
        assert r"^[a-z0-9]+(-[a-z0-9]+)*$" in str(exc.value.message)
        assert _validate_key_alias_format("prod-key-001") is None
        assert _validate_key_alias_format(None) is None

    def test_configured_pattern_must_match_the_whole_alias(self, monkeypatch: pytest.MonkeyPatch) -> None:
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "key_alias_pattern", r"team-[a-z]+")
        _validate_key_alias_format("team-search")
        for partial_match in ("team-search-2", "xteam-search"):
            with pytest.raises(ProxyException):
                _validate_key_alias_format(partial_match)

    def test_configured_pattern_replaces_the_builtin_rule(self, monkeypatch: pytest.MonkeyPatch) -> None:
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "enable_key_alias_format_validation", True)
        monkeypatch.setattr(litellm, "key_alias_pattern", r"^[a-z ]+$")
        _validate_key_alias_format("alias with spaces")
        with pytest.raises(ProxyException) as exc:
            _validate_key_alias_format("Uppercase")
        assert "key_alias_pattern" in str(exc.value.message)

    def test_configured_pattern_keeps_the_baseline_safety_check(self, monkeypatch: pytest.MonkeyPatch) -> None:
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "key_alias_pattern", r".*")
        with pytest.raises(ProxyException) as exc:
            _validate_key_alias_format("../../../other-app/creds")
        assert str(exc.value.code) == "400"
        assert "key_alias_pattern" not in str(exc.value.message)

    def test_configured_pattern_bounds_the_alias_length(self, monkeypatch: pytest.MonkeyPatch) -> None:
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        monkeypatch.setattr(litellm, "key_alias_pattern", r"^[a-z]+$")
        _validate_key_alias_format("a" * 255)
        with pytest.raises(ProxyException) as exc:
            _validate_key_alias_format("a" * 256)
        assert str(exc.value.code) == "400"
        assert "at most 255 characters" in str(exc.value.message)


@pytest.mark.asyncio
async def test_check_org_key_limits_on_update_within_bounds():
    """
    Test that _check_org_key_limits works with UpdateKeyRequest when updating
    a key's TPM/RPM limits within organization bounds.
    """
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[]
    )

    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-update-1",
        organization_alias="test-org",
        budget_id="budget-123",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-123",
            tpm_limit=20000,
            rpm_limit=2000,
        ),
    )

    data = UpdateKeyRequest(
        key="sk-test-key",
        tpm_limit=10000,
        rpm_limit=1000,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
        organization_id="test-org-update-1",
    )

    # Should not raise any exception
    await _check_org_key_limits(
        org_table=org_table,
        data=data,
        prisma_client=mock_prisma_client,
    )

    mock_prisma_client.db.litellm_verificationtoken.find_many.assert_called_once_with(
        where={"organization_id": "test-org-update-1"}
    )


@pytest.mark.asyncio
async def test_check_org_key_limits_on_update_overallocation():
    """
    Test that _check_org_key_limits raises HTTPException when updating a key
    would exceed organization TPM limits.
    """
    from litellm.proxy._types import hash_token as _hash_token

    existing_key = MagicMock()
    existing_key.token = _hash_token("sk-other-key")
    existing_key.tpm_limit = 15000
    existing_key.rpm_limit = 1500
    existing_key.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[existing_key]
    )

    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-update-2",
        organization_alias="test-org",
        budget_id="budget-456",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-456",
            tpm_limit=20000,
            rpm_limit=2000,
        ),
    )

    data = UpdateKeyRequest(
        key="sk-test-key",
        tpm_limit=10000,  # 15000 + 10000 = 25000 > 20000
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
        organization_id="test-org-update-2",
    )

    with pytest.raises(HTTPException) as exc:
        await _check_org_key_limits(
            org_table=org_table,
            data=data,
            prisma_client=mock_prisma_client,
        )
    assert exc.value.status_code == 400
    assert "TPM limit" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_check_org_key_limits_on_update_excludes_self():
    """
    Test that _check_org_key_limits excludes the key being updated from the
    allocated totals. Without this, the key's current limits would be
    double-counted: once from find_many and once from data.tpm_limit/rpm_limit.
    """
    from litellm.proxy._types import hash_token

    # The key being updated is returned by find_many with its current limits.
    # In the DB, token is stored as a SHA-256 hash of the raw key.
    self_key = MagicMock()
    self_key.token = hash_token("sk-test-key")
    self_key.tpm_limit = 10000
    self_key.rpm_limit = 1000
    self_key.metadata = {}

    # Another key in the org
    other_key = MagicMock()
    other_key.token = hash_token("sk-other-key")
    other_key.tpm_limit = 5000
    other_key.rpm_limit = 500
    other_key.metadata = {}

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[self_key, other_key]
    )

    org_table = LiteLLM_OrganizationTable(
        organization_id="test-org-self",
        organization_alias="test-org",
        budget_id="budget-789",
        models=["gpt-4"],
        created_by="admin",
        updated_by="admin",
        litellm_budget_table=LiteLLM_BudgetTable(
            budget_id="budget-789",
            tpm_limit=20000,
            rpm_limit=2000,
        ),
    )

    # Updating the key to 12000 TPM. Other key uses 5000, so total = 17000 < 20000.
    # Without the fix, this would be 10000 (self) + 5000 (other) + 12000 = 27000 > 20000.
    data = UpdateKeyRequest(
        key="sk-test-key",
        tpm_limit=12000,
        rpm_limit=1200,
        tpm_limit_type="guaranteed_throughput",
        rpm_limit_type="guaranteed_throughput",
        organization_id="test-org-self",
    )

    # Should not raise - the key's own limits should be excluded from the sum
    await _check_org_key_limits(
        org_table=org_table,
        data=data,
        prisma_client=mock_prisma_client,
    )


def test_update_key_skips_org_check_when_no_throughput_fields_changed():
    """
    Test that the org limit check guard condition correctly skips validation
    when only non-throughput fields change on a key that belongs to an org.
    This prevents blocking updates when the org has been deleted.
    """

    def _check_throughput_changed(data: UpdateKeyRequest) -> bool:
        return (
            data.organization_id is not None
            or data.tpm_limit is not None
            or data.rpm_limit is not None
            or data.tpm_limit_type is not None
            or data.rpm_limit_type is not None
        )

    # Updating only key_alias — no throughput fields changed
    data = UpdateKeyRequest(key="sk-test-key", key_alias="new-alias")
    assert _check_throughput_changed(data) is False

    # Updating tpm_limit — throughput field changed
    data_with_tpm = UpdateKeyRequest(key="sk-test-key", tpm_limit=5000)
    assert _check_throughput_changed(data_with_tpm) is True

    # Updating organization_id — org change triggers check
    data_with_org = UpdateKeyRequest(key="sk-test-key", organization_id="new-org")
    assert _check_throughput_changed(data_with_org) is True

    # Updating tpm_limit_type — limit type change triggers check
    data_with_tpm_type = UpdateKeyRequest(
        key="sk-test-key", tpm_limit_type="guaranteed_throughput"
    )
    assert _check_throughput_changed(data_with_tpm_type) is True

    # Updating rpm_limit_type — limit type change triggers check
    data_with_rpm_type = UpdateKeyRequest(
        key="sk-test-key", rpm_limit_type="guaranteed_throughput"
    )
    assert _check_throughput_changed(data_with_rpm_type) is True


def test_update_key_request_has_organization_id():
    """
    Test that UpdateKeyRequest accepts organization_id field.
    """
    data = UpdateKeyRequest(
        key="sk-test-key",
        organization_id="test-org-123",
    )
    assert data.organization_id == "test-org-123"

    # Also verify it defaults to None
    data_no_org = UpdateKeyRequest(key="sk-test-key")
    assert data_no_org.organization_id is None


# ============================================================================
# Tests for admin-only access on /key/block, /key/unblock, /key/update max_budget
# ============================================================================


def _setup_block_unblock_mocks(monkeypatch, mock_key_team_id=None):
    """Helper to set up common mocks for block/unblock tests."""
    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = (
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    )

    mock_key_record = MagicMock()
    mock_key_record.token = test_hashed_token
    mock_key_record.blocked = False
    mock_key_record.team_id = mock_key_team_id
    mock_key_record.model_dump_json.return_value = (
        f'{{"token": "{test_hashed_token}", "blocked": false}}'
    )

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_record
    )
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=mock_key_record
    )

    mock_key_object = MagicMock()
    mock_key_object.blocked = True

    def mock_hash_token(token):
        if token.startswith("sk-"):
            return test_hashed_token
        return token

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    async def mock_delete_cache_key_object(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        mock_delete_cache_key_object,
    )

    return mock_prisma_client, test_hashed_token


@pytest.mark.asyncio
async def test_block_key_rejected_for_internal_user(monkeypatch):
    """Internal users should not be able to block keys."""
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    _setup_block_unblock_mocks(monkeypatch)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    with pytest.raises(HTTPException) as exc:
        await block_key(
            data=BlockKeyRequest(key="sk-test123456789"),
            http_request=mock_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc.value.status_code == 403
    assert "Only proxy admins, team admins, or org admins" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_unblock_key_rejected_for_internal_user(monkeypatch):
    """Internal users should not be able to unblock keys."""
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import unblock_key

    _setup_block_unblock_mocks(monkeypatch)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    with pytest.raises(HTTPException) as exc:
        await unblock_key(
            data=BlockKeyRequest(key="sk-test123456789"),
            http_request=mock_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert exc.value.status_code == 403
    assert "Only proxy admins, team admins, or org admins" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_block_key_allowed_for_proxy_admin(monkeypatch):
    """Proxy admins should be able to block keys."""
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    _setup_block_unblock_mocks(monkeypatch)

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin_user",
    )

    result = await block_key(
        data=BlockKeyRequest(key="sk-test123456789"),
        http_request=mock_request,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )
    assert result is not None


@pytest.mark.asyncio
async def test_block_key_allowed_for_team_admin(monkeypatch):
    """Team admins should be able to block keys belonging to their team."""
    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    team_id = "team-123"
    _setup_block_unblock_mocks(monkeypatch, mock_key_team_id=team_id)

    # Mock get_team_object to return a team where the user is admin
    team_obj = LiteLLM_TeamTableCachedObj(
        team_id=team_id,
        members_with_roles=[
            Member(user_id="team_admin_user", role="admin"),
        ],
    )

    async def mock_get_team_object(**kwargs):
        return team_obj

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )

    mock_request = MagicMock()
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-teamadmin",
        user_id="team_admin_user",
    )

    result = await block_key(
        data=BlockKeyRequest(key="sk-test123456789"),
        http_request=mock_request,
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )
    assert result is not None


@pytest.mark.asyncio
async def test_update_key_max_budget_rejected_for_internal_user(monkeypatch):
    """Internal users should not be able to modify max_budget on keys."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = AsyncMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = (
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    )

    # Mock existing key row
    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = "internal_user"
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.models = []
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "internal_user",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    mock_request = MagicMock()
    mock_request.query_params = {}
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key=test_hashed_token, max_budget=999999),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert str(exc.value.code) == "403"
    assert "Only proxy admins, team admins, or org admins" in str(exc.value.message)


@pytest.mark.asyncio
async def test_update_key_non_budget_fields_allowed_for_internal_user(monkeypatch):
    """Internal users should still be able to update non-budget fields on their own keys."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = AsyncMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = (
        "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    )

    # Mock existing key row
    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = "internal_user"
    mock_existing_key.created_by = "internal_user"
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = None
    mock_existing_key.models = []
    mock_existing_key.metadata = {}
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "internal_user",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_updated_key = MagicMock()
    mock_updated_key.token = test_hashed_token
    mock_updated_key.key_alias = "my-alias"

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.update_data = AsyncMock(return_value=mock_updated_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    def mock_hash_token(token):
        return test_hashed_token

    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", mock_hash_token)

    async def mock_delete_cache_key_object(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        mock_delete_cache_key_object,
    )

    # Mock _enforce_unique_key_alias to avoid DB call
    async def mock_enforce_unique_key_alias(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints._enforce_unique_key_alias",
        mock_enforce_unique_key_alias,
    )

    mock_request = MagicMock()
    mock_request.query_params = {}
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    # Updating key_alias (non-budget field) should succeed
    result = await update_key_fn(
        request=mock_request,
        data=UpdateKeyRequest(key=test_hashed_token, key_alias="my-alias"),
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )

    assert result is not None


@pytest.mark.asyncio
async def test_update_key_throttle_on_budget_exceeded_rejected_for_internal_user(
    monkeypatch,
):
    """Security regression: throttle_on_budget_exceeded turns an admin-imposed
    hard budget block into a soft throttle that keeps spending past max_budget,
    so it is a budget-enforcement change. A non-admin key owner (same setup that
    is allowed to change non-budget fields via the caller_is_creator shortcut)
    must NOT be able to self-opt-in to it; it has to route through the admin-only
    _check_key_admin_access and return 403. Without treating the flag as a budget
    change this update would succeed, letting the owner bypass their own cap."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = AsyncMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"

    # Owner of the key (created_by == user_id) so caller_is_creator is True.
    # This is exactly the setup that is allowed to change non-budget fields;
    # the throttle flag must still be rejected.
    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = "internal_user"
    mock_existing_key.created_by = "internal_user"
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = None
    mock_existing_key.models = []
    mock_existing_key.metadata = {}
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "internal_user",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=mock_existing_key)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache)
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    mock_request = MagicMock()
    mock_request.query_params = {}
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(
                key=test_hashed_token,
                throttle_on_budget_exceeded=True,
            ),
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert str(exc.value.code) == "403"
    assert "Only proxy admins can enable throttle_on_budget_exceeded" in str(exc.value.message)


@pytest.mark.asyncio
async def test_update_key_throttle_unchanged_allows_non_budget_edit_for_internal_user(
    monkeypatch,
):
    """A non-admin owner editing a non-budget field must not be blocked just
    because the UI resends throttle_on_budget_exceeded unchanged (the edit form
    always includes it). Only the transition to enabled is admin-gated, so an
    unchanged False here leaves the key owner's non-budget edit working."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    mock_user_api_key_cache = AsyncMock()
    mock_proxy_logging_obj = MagicMock()

    test_hashed_token = "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"

    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = "internal_user"
    mock_existing_key.created_by = "internal_user"
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = None
    mock_existing_key.models = []
    mock_existing_key.metadata = {"throttle_on_budget_exceeded": False}
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "internal_user",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_updated_key = MagicMock()
    mock_updated_key.token = test_hashed_token
    mock_updated_key.key_alias = "my-alias"

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.update_data = AsyncMock(return_value=mock_updated_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=mock_existing_key)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache)
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", mock_proxy_logging_obj)
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", lambda token: test_hashed_token)

    async def _noop(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        _noop,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints._enforce_unique_key_alias",
        _noop,
    )

    mock_request = MagicMock()
    mock_request.query_params = {}
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="internal_user",
    )

    result = await update_key_fn(
        request=mock_request,
        data=UpdateKeyRequest(
            key=test_hashed_token,
            key_alias="my-alias",
            throttle_on_budget_exceeded=False,
        ),
        user_api_key_dict=user_api_key_dict,
        litellm_changed_by=None,
    )

    assert result is not None


@pytest.mark.asyncio
async def test_update_key_non_budget_rejects_cross_user_modification(monkeypatch):
    """Regression: previously _check_key_admin_access was gated on
    max_budget/spend changes only, so an internal user could rewrite any
    OTHER field (alias, models, tpm_limit, blocked, metadata, …) on any
    key they weren't admin of as long as they avoided budget/spend. This
    confirms that a non-admin user updating a key that belongs to another
    user fails with 403 even for non-budget fields."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    mock_prisma_client = AsyncMock()
    test_hashed_token = "cafebabe" * 8

    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = "victim_user"  # owned by someone else
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = "original"
    mock_existing_key.models = []
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "victim_user",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.hash_token", lambda t: test_hashed_token
    )

    mock_request = MagicMock()
    mock_request.query_params = {}
    attacker = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-attacker",
        user_id="attacker_user",  # NOT the owner
    )

    # Trying to blanket-rewrite a non-budget field on someone else's key
    # must now fail.
    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(
                key=test_hashed_token, key_alias="pwned", blocked=True
            ),
            user_api_key_dict=attacker,
            litellm_changed_by=None,
        )
    assert str(exc.value.code) == "403"


@pytest.mark.asyncio
async def test_update_key_creator_reassigned_key_blocked(monkeypatch):
    """Regression: creator who no longer owns the key (user_id ≠ caller) must
    not bypass _check_key_admin_access via the caller_is_creator shortcut."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    test_hashed_token = "aabbccdd" * 8
    mock_prisma_client = AsyncMock()

    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.created_by = "demoted-admin"  # creator
    mock_existing_key.user_id = "victim-user"  # reassigned to someone else
    mock_existing_key.team_id = None
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = "original"
    mock_existing_key.models = []
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": "victim-user",
        "created_by": "demoted-admin",
        "team_id": None,
        "max_budget": 10.0,
    }

    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.hash_token", lambda t: test_hashed_token
    )

    demoted_admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-demoted",
        user_id="demoted-admin",
    )

    mock_request = MagicMock()
    mock_request.query_params = {}

    with pytest.raises(Exception, match='User can only create keys for themselves\\. Got') as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key=test_hashed_token, key_alias="hijacked"),
            user_api_key_dict=demoted_admin,
            litellm_changed_by=None,
        )
    assert str(exc.value.code) == "403"


@pytest.mark.asyncio
async def test_update_key_team_member_with_permission_can_update_non_budget(
    monkeypatch,
):
    """A team member whose team grants /key/update in member_permissions can
    update non-budget fields on a team key even though they are not a team
    admin. Regression: the cross-key admin check was over-broad and rejected
    this documented path."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    test_hashed_token = "deadbeef" * 8
    team_id = "team-with-update-grant"
    member_user_id = "team-member-user"

    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = None  # team-scoped key (no owning user)
    mock_existing_key.team_id = team_id
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = "original"
    mock_existing_key.models = []
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": None,
        "team_id": team_id,
        "max_budget": 10.0,
    }

    team_table = LiteLLM_TeamTableCachedObj(
        team_id=team_id,
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="some-team-admin", role="admin"),
            Member(user_id=member_user_id, role="user"),
        ],
        team_member_permissions=["/key/update", "/key/info"],
    )

    mock_updated_key = MagicMock()
    mock_updated_key.token = test_hashed_token
    mock_updated_key.key_alias = "renamed-by-member"

    mock_prisma_client = AsyncMock()
    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.update_data = AsyncMock(return_value=mock_updated_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    async def mock_enforce_unique_key_alias(**kwargs):
        pass

    async def mock_delete_cache_key_object(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_helpers.team_member_permission_checks.get_team_object",
        mock_get_team_object,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints._enforce_unique_key_alias",
        mock_enforce_unique_key_alias,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        mock_delete_cache_key_object,
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.hash_token", lambda t: test_hashed_token
    )

    mock_request = MagicMock()
    mock_request.query_params = {}
    team_member = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-team-member",
        user_id=member_user_id,
        team_id=team_id,
    )

    # Non-budget update on a team key by a team member with /key/update
    # permission should succeed.
    result = await update_key_fn(
        request=mock_request,
        data=UpdateKeyRequest(key=test_hashed_token, key_alias="renamed-by-member"),
        user_api_key_dict=team_member,
        litellm_changed_by=None,
    )

    assert result is not None


@pytest.mark.asyncio
async def test_update_key_team_member_cannot_change_budget(monkeypatch):
    """A team member with /key/update in member_permissions still cannot
    change max_budget — budget/spend changes require team/org admin. The
    member_permissions bypass only applies to non-budget fields."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    test_hashed_token = "feedface" * 8
    team_id = "team-with-update-grant"
    member_user_id = "team-member-user"

    mock_existing_key = MagicMock()
    mock_existing_key.token = test_hashed_token
    mock_existing_key.user_id = None  # team-scoped key (no owning user)
    mock_existing_key.team_id = team_id
    mock_existing_key.project_id = None
    mock_existing_key.max_budget = 10.0
    mock_existing_key.key_alias = "original"
    mock_existing_key.models = []
    mock_existing_key.model_dump.return_value = {
        "token": test_hashed_token,
        "user_id": None,
        "team_id": team_id,
        "max_budget": 10.0,
    }

    team_table = LiteLLM_TeamTableCachedObj(
        team_id=team_id,
        team_alias="test-team",
        tpm_limit=None,
        rpm_limit=None,
        max_budget=None,
        spend=0.0,
        models=[],
        blocked=False,
        members_with_roles=[
            Member(user_id="some-team-admin", role="admin"),
            Member(user_id=member_user_id, role="user"),
        ],
        team_member_permissions=["/key/update", "/key/info"],
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.get_data = AsyncMock(return_value=mock_existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_existing_key
    )

    async def mock_get_team_object(*args, **kwargs):
        return team_table

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        mock_get_team_object,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_helpers.team_member_permission_checks.get_team_object",
        mock_get_team_object,
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.hash_token", lambda t: test_hashed_token
    )

    mock_request = MagicMock()
    mock_request.query_params = {}
    team_member = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-team-member",
        user_id=member_user_id,
        team_id=team_id,
    )

    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key=test_hashed_token, max_budget=500.0),
            user_api_key_dict=team_member,
            litellm_changed_by=None,
        )
    assert str(exc.value.code) == "403"


# ============================================================================
# LIT-1884: Internal users cannot create invalid keys
# ============================================================================


class TestLIT1884KeyGenerateValidation:
    """Tests for LIT-1884: internal users should not be able to generate invalid keys."""

    @pytest.mark.asyncio
    async def test_internal_user_generate_key_no_user_id_auto_assigns(self):
        """
        When an internal_user calls /key/generate without user_id,
        the caller's user_id should be auto-assigned before reaching
        _common_key_generation_helper.
        """
        mock_prisma_client = AsyncMock()

        data = GenerateKeyRequest(key_alias="test-alias")
        assert data.user_id is None

        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        # Patch _common_key_generation_helper to avoid needing full DB mocks.
        # We just want to verify user_id is set before we reach this point.
        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )

        # The data object should have been mutated to include the caller's user_id
        assert data.user_id == "internal-user-123"

    @pytest.mark.asyncio
    async def test_internal_user_generate_key_invalid_team_id_rejected(self):
        """
        When an internal_user provides a non-existent team_id,
        key/generate should raise ProxyException with status 400.
        """
        mock_prisma_client = AsyncMock()

        data = GenerateKeyRequest(
            key_alias="test-alias",
            team_id="nonexistent-team-id",
        )

        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
                AsyncMock(side_effect=Exception("Team not found")),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await generate_key_fn(
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
            assert str(exc_info.value.code) == "400"
            assert "Team not found" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_admin_generate_key_invalid_team_id_allowed(self):
        """
        Admin callers should be allowed to create keys with any team_id,
        even if the team doesn't exist (team_table=None is OK for admins).
        """
        data = GenerateKeyRequest(
            key_alias="admin-key",
            team_id="nonexistent-team-id",
            user_id="admin-user",
        )

        user_api_key_dict = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
                AsyncMock(side_effect=Exception("Team not found")),
            ),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            # Should NOT raise — admin bypasses team validation
            result = await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )
            assert result is not None

    @pytest.mark.asyncio
    async def test_admin_generate_key_no_user_id_not_auto_assigned(self):
        """
        Admin callers should NOT have user_id auto-assigned — they may
        intentionally create keys without a user_id.
        """
        data = GenerateKeyRequest(key_alias="admin-unbound-key")
        assert data.user_id is None

        user_api_key_dict = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )

        # user_id should remain None for admin
        assert data.user_id is None

    def test_key_generation_check_non_admin_no_team_table_raises(self):
        """
        key_generation_check should raise 400 for non-admin when team_table is None
        and key_generation_settings is not set.
        """
        data = GenerateKeyRequest(team_id="some-team-id")
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with patch.object(litellm, "key_generation_settings", None):
            with pytest.raises(HTTPException) as exc_info:
                key_generation_check(
                    team_table=None,
                    user_api_key_dict=user_api_key_dict,
                    data=data,
                    route="key_generate",
                )
            assert exc_info.value.status_code == 400
            assert "Unable to find team object" in str(exc_info.value.detail)

    def test_key_generation_check_admin_no_team_table_allowed(self):
        """
        key_generation_check should allow admin to proceed even when team_table is None.
        """
        data = GenerateKeyRequest(team_id="some-team-id")
        user_api_key_dict = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        with patch.object(litellm, "key_generation_settings", None):
            result = key_generation_check(
                team_table=None,
                user_api_key_dict=user_api_key_dict,
                data=data,
                route="key_generate",
            )
            assert result is True


class TestLIT1884KeyUpdateValidation:
    """Tests for LIT-1884: internal users should not be able to update keys to remove user_id or set invalid team."""

    @pytest.mark.asyncio
    async def test_internal_user_cannot_remove_user_id(self):
        """
        Non-admin users should not be able to set user_id to empty string (remove it).
        """
        data = UpdateKeyRequest(key="sk-test-key", user_id="")
        existing_key_row = MagicMock()
        existing_key_row.user_id = "internal-user-123"
        existing_key_row.token = "hashed_token"
        existing_key_row.team_id = None

        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with pytest.raises(HTTPException) as exc_info:
            await _validate_update_key_data(
                data=data,
                existing_key_row=existing_key_row,
                user_api_key_dict=user_api_key_dict,
                llm_router=None,
                premium_user=False,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        assert exc_info.value.status_code == 403
        assert "cannot remove the user_id" in str(exc_info.value.detail)

    @pytest.mark.asyncio
    async def test_internal_user_cannot_set_invalid_team_id(self):
        """
        Non-admin users should not be able to update a key to a non-existent team.
        get_team_object raises HTTPException(404) when team doesn't exist in DB.
        """
        data = UpdateKeyRequest(key="sk-test-key", team_id="nonexistent-team")
        existing_key_row = MagicMock()
        existing_key_row.user_id = "internal-user-123"
        existing_key_row.token = "hashed_token"
        existing_key_row.team_id = None
        existing_key_row.organization_id = None
        existing_key_row.project_id = None

        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
            AsyncMock(
                side_effect=HTTPException(
                    status_code=404,
                    detail="Team doesn't exist in db. Team=nonexistent-team.",
                )
            ),
        ):
            with pytest.raises(HTTPException) as exc_info:
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing_key_row,
                    user_api_key_dict=user_api_key_dict,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
            assert exc_info.value.status_code == 404
            assert "Team doesn't exist" in str(exc_info.value.detail)

    @pytest.mark.asyncio
    async def test_admin_can_remove_user_id(self):
        """
        Admin users should be allowed to set user_id to empty string.
        """
        data = UpdateKeyRequest(key="sk-test-key", user_id="")
        existing_key_row = MagicMock()
        existing_key_row.user_id = "some-user"
        existing_key_row.token = "hashed_token"
        existing_key_row.team_id = None
        existing_key_row.organization_id = None
        existing_key_row.project_id = None

        user_api_key_dict = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        mock_prisma_client = AsyncMock()

        # Should NOT raise
        await _validate_update_key_data(
            data=data,
            existing_key_row=existing_key_row,
            user_api_key_dict=user_api_key_dict,
            llm_router=None,
            premium_user=False,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )


class TestLIT4891SafePresetKeyTypeTransition:
    def _make_existing_key(self, allowed_routes):
        row = MagicMock()
        row.user_id = "internal-user-123"
        row.created_by = "internal-user-123"
        row.token = "hashed_token"
        row.team_id = None
        row.max_budget = None
        row.spend = 0.0
        row.organization_id = None
        row.project_id = None
        row.allowed_routes = allowed_routes
        return row

    def _make_auth(self):
        return UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

    async def _run_update(self, data, existing_key_row):
        try:
            await _validate_update_key_data(
                data=data,
                existing_key_row=existing_key_row,
                user_api_key_dict=self._make_auth(),
                llm_router=None,
                premium_user=False,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        except HTTPException as exc:
            return exc
        return None

    def _assert_routes_403(self, exc):
        assert exc is not None
        assert exc.status_code == 403
        assert "Only proxy admins can set" in str(exc.detail)

    @pytest.mark.asyncio
    async def test_non_admin_owner_can_clear_safe_preset_to_full_access(self):
        assert (
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=[]),
                existing_key_row=self._make_existing_key(allowed_routes=["llm_api_routes"]),
            )
            is None
        )

    @pytest.mark.asyncio
    async def test_non_admin_owner_can_switch_full_access_to_safe_preset(self):
        assert (
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=["llm_api_routes"]),
                existing_key_row=self._make_existing_key(allowed_routes=[]),
            )
            is None
        )

    @pytest.mark.asyncio
    async def test_non_admin_owner_can_narrow_to_read_only_preset(self):
        assert (
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=["info_routes"]),
                existing_key_row=self._make_existing_key(allowed_routes=["llm_api_routes"]),
            )
            is None
        )

    @pytest.mark.asyncio
    async def test_non_admin_can_resend_read_only_preset_unchanged(self):
        assert (
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=["info_routes"]),
                existing_key_row=self._make_existing_key(allowed_routes=["info_routes"]),
            )
            is None
        )

    @pytest.mark.asyncio
    async def test_non_admin_cannot_widen_read_only_key_to_full_access(self):
        self._assert_routes_403(
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=[]),
                existing_key_row=self._make_existing_key(allowed_routes=["info_routes"]),
            )
        )

    @pytest.mark.asyncio
    async def test_non_admin_cannot_widen_read_only_key_to_llm_api(self):
        self._assert_routes_403(
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=["llm_api_routes"]),
                existing_key_row=self._make_existing_key(allowed_routes=["info_routes"]),
            )
        )

    @pytest.mark.asyncio
    async def test_non_admin_cannot_clear_custom_route_restriction(self):
        self._assert_routes_403(
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=[]),
                existing_key_row=self._make_existing_key(allowed_routes=["/chat/completions"]),
            )
        )

    @pytest.mark.asyncio
    async def test_non_admin_cannot_set_non_preset_routes(self):
        self._assert_routes_403(
            await self._run_update(
                data=UpdateKeyRequest(key="sk-test", allowed_routes=["management_routes"]),
                existing_key_row=self._make_existing_key(allowed_routes=["llm_api_routes"]),
            )
        )


class TestKeyOwnerPrivilegeEscalation:
    """
    Policy:
    - created_by == caller → can edit any non-budget field without admin
    - created_by != caller (assigned user) → must pass admin check for any edit
    - budget changes (max_budget/spend) → always require admin
    - PROXY_ADMIN → unrestricted
    """

    def _make_existing_key(self, user_id="creator-123", created_by="creator-123"):
        row = MagicMock()
        # user_id must be set explicitly — MagicMock auto-attrs are not None and
        # trip the _is_allowed_to_make_key_request assert before our check runs.
        row.user_id = user_id
        row.created_by = created_by
        row.token = "hashed_token"
        row.team_id = None
        row.max_budget = None
        row.spend = 0.0
        row.organization_id = None
        row.project_id = None
        return row

    def _make_auth(self, user_id="creator-123"):
        return UserAPIKeyAuth(
            user_id=user_id,
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

    @pytest.mark.asyncio
    async def test_assigned_user_blocked_from_any_edit(self):
        """User who did not create the key cannot edit it at all."""
        data = UpdateKeyRequest(key="sk-test", key_alias="hacked")
        # user_id matches caller so _is_allowed_to_make_key_request passes,
        # but created_by != caller so our creator check requires admin.
        existing = self._make_existing_key(
            user_id="assigned-user", created_by="admin-456"
        )
        auth = self._make_auth(user_id="assigned-user")

        mock_check = AsyncMock(
            side_effect=HTTPException(status_code=403, detail="Not authorized")
        )
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            with pytest.raises(HTTPException) as exc_info:
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing,
                    user_api_key_dict=auth,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
        assert exc_info.value.status_code == 403
        mock_check.assert_called_once()

    @pytest.mark.asyncio
    async def test_creator_cannot_reset_own_spend_to_stale_value(self):
        """Submitting `spend` equal to the stale DB value must still require
        admin. The DB spend lags the live cross-pod counter, so an
        "unchanged" spend on the non-admin path would let the creator
        overwrite the live counter below real usage. Any explicit `spend`
        is a budget change, regardless of value match."""
        existing = self._make_existing_key(created_by="creator-123")
        existing.spend = 0.0
        # spend equals the stale DB value (0.0) — the old `!=` gate skipped
        # the admin check here.
        data = UpdateKeyRequest(key="sk-test", spend=0.0)
        auth = self._make_auth(user_id="creator-123")

        mock_check = AsyncMock(
            side_effect=HTTPException(status_code=403, detail="Not authorized")
        )
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            with pytest.raises(HTTPException):
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing,
                    user_api_key_dict=auth,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
        mock_check.assert_called_once()

    @pytest.mark.asyncio
    async def test_assigned_user_blocked_from_model_escalation(self):
        data = UpdateKeyRequest(key="sk-test", models=["gpt-4", "claude-opus"])
        existing = self._make_existing_key(
            user_id="assigned-user", created_by="admin-456"
        )
        auth = self._make_auth(user_id="assigned-user")

        mock_check = AsyncMock(
            side_effect=HTTPException(status_code=403, detail="Not authorized")
        )
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            with pytest.raises(HTTPException):
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing,
                    user_api_key_dict=auth,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
        mock_check.assert_called_once()

    @pytest.mark.asyncio
    async def test_creator_can_edit_own_key(self):
        """Key creator can update any non-budget field without admin."""
        data = UpdateKeyRequest(
            key="sk-test", models=["gpt-4"], rpm_limit=500, key_alias="my-key"
        )
        existing = self._make_existing_key(created_by="creator-123")
        auth = self._make_auth(user_id="creator-123")

        mock_check = AsyncMock()
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            await _validate_update_key_data(
                data=data,
                existing_key_row=existing,
                user_api_key_dict=auth,
                llm_router=None,
                premium_user=False,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        mock_check.assert_not_called()

    @pytest.mark.asyncio
    async def test_creator_cannot_change_own_budget(self):
        """Budget changes require admin even for the key creator."""
        data = UpdateKeyRequest(key="sk-test", max_budget=9999.0)
        existing = self._make_existing_key(created_by="creator-123")
        existing.max_budget = 10.0
        auth = self._make_auth(user_id="creator-123")

        mock_check = AsyncMock(
            side_effect=HTTPException(status_code=403, detail="Not authorized")
        )
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            with pytest.raises(HTTPException):
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing,
                    user_api_key_dict=auth,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
        mock_check.assert_called_once()

    @pytest.mark.asyncio
    @pytest.mark.parametrize("cleared_value", [[], None])
    async def test_creator_cannot_clear_own_budget_limits(self, cleared_value):
        """Clearing budget_limits is a budget change and requires admin."""
        data = UpdateKeyRequest(key="sk-test", budget_limits=cleared_value)
        existing = self._make_existing_key(created_by="creator-123")
        auth = self._make_auth(user_id="creator-123")

        mock_check = AsyncMock(
            side_effect=HTTPException(status_code=403, detail="Not authorized")
        )
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            with pytest.raises(HTTPException):
                await _validate_update_key_data(
                    data=data,
                    existing_key_row=existing,
                    user_api_key_dict=auth,
                    llm_router=None,
                    premium_user=False,
                    prisma_client=AsyncMock(),
                    user_api_key_cache=MagicMock(),
                )
        mock_check.assert_called_once()

    @pytest.mark.asyncio
    async def test_admin_can_clear_budget_limits(self):
        data = UpdateKeyRequest(key="sk-test", budget_limits=[])
        existing = self._make_existing_key(created_by="someone-else")
        auth = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        mock_check = AsyncMock()
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            await _validate_update_key_data(
                data=data,
                existing_key_row=existing,
                user_api_key_dict=auth,
                llm_router=None,
                premium_user=False,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        mock_check.assert_not_called()

    @pytest.mark.asyncio
    async def test_admin_can_update_any_field(self):
        data = UpdateKeyRequest(key="sk-test", models=["gpt-4"], max_budget=999.0)
        existing = self._make_existing_key(created_by="someone-else")
        existing.max_budget = 1.0
        auth = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )

        mock_check = AsyncMock()
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            mock_check,
        ):
            await _validate_update_key_data(
                data=data,
                existing_key_row=existing,
                user_api_key_dict=auth,
                llm_router=None,
                premium_user=False,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        mock_check.assert_not_called()


class TestKeyAliasSkipValidationOnUnchanged:
    """
    Test that updating/regenerating a key without changing its key_alias
    does NOT re-validate the alias. This prevents legacy aliases (created
    before stricter validation rules) from blocking edits to other fields.
    """

    @pytest.fixture(autouse=True)
    def enable_validation(self, monkeypatch: pytest.MonkeyPatch) -> None:
        monkeypatch.setattr(litellm, "enable_key_alias_format_validation", True)

    @pytest.fixture
    def mock_prisma(self):
        prisma = MagicMock()
        prisma.db = MagicMock()
        prisma.db.litellm_verificationtoken = MagicMock()
        prisma.get_data = AsyncMock(return_value=None)  # no duplicate alias
        prisma.update_data = AsyncMock(return_value=None)
        prisma.jsonify_object = MagicMock(side_effect=lambda data: data)
        return prisma

    @pytest.fixture
    def existing_key_with_legacy_alias(self):
        """A key whose alias contains '@' — valid now, but simulates a legacy alias."""
        return LiteLLM_VerificationToken(
            token="hashed_token_123",
            key_alias="[email protected]",
            team_id="team-1",
            models=[],
            max_budget=100.0,
        )

    @pytest.mark.asyncio
    async def test_update_key_unchanged_legacy_alias_passes(
        self, mock_prisma, existing_key_with_legacy_alias
    ):
        """
        Updating a key without changing its key_alias should skip format
        validation — even if the alias wouldn't pass current rules.
        """
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        # Temporarily make the regex reject '@' to simulate stricter rules
        import re
        from litellm.proxy.management_endpoints import key_management_endpoints as mod

        original_pattern = mod._KEY_ALIAS_PATTERN
        mod._KEY_ALIAS_PATTERN = re.compile(
            r"^[a-zA-Z0-9][a-zA-Z0-9_\-/\.]{0,253}[a-zA-Z0-9]$"
        )
        try:
            # Confirm the alias WOULD fail validation directly
            with pytest.raises(ProxyException):
                _validate_key_alias_format("[email protected]")

            # But prepare_key_update_data + the skip logic should allow it
            # Simulate what update_key_fn does: alias is in non_default_values
            # but matches existing_key_row.key_alias => skip validation
            existing_alias = existing_key_with_legacy_alias.key_alias
            new_alias = "[email protected]"  # same as existing
            assert new_alias == existing_alias  # unchanged

            # This is the core logic from update_key_fn:
            if new_alias != existing_alias:
                _validate_key_alias_format(new_alias)
            # No exception raised — test passes
        finally:
            mod._KEY_ALIAS_PATTERN = original_pattern

    @pytest.mark.asyncio
    async def test_update_key_changed_alias_still_validated(
        self, mock_prisma, existing_key_with_legacy_alias
    ):
        """
        When the alias IS being changed, validation should still run.
        """
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        existing_alias = existing_key_with_legacy_alias.key_alias
        new_alias = "!invalid!"

        assert new_alias != existing_alias
        with pytest.raises(ProxyException):
            _validate_key_alias_format(new_alias)

    @pytest.mark.asyncio
    async def test_update_key_changed_to_valid_alias_passes(
        self, mock_prisma, existing_key_with_legacy_alias
    ):
        """
        Changing the alias to a new valid value should pass validation.
        """
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        existing_alias = existing_key_with_legacy_alias.key_alias
        new_alias = "new-valid-alias"

        assert new_alias != existing_alias
        # Should not raise
        if new_alias != existing_alias:
            _validate_key_alias_format(new_alias)

    @pytest.mark.asyncio
    async def test_update_key_alias_none_skips_validation(self):
        """
        When key_alias is not in the update payload (None), validation
        should be skipped regardless.
        """
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _validate_key_alias_format,
        )

        # None alias should always pass
        _validate_key_alias_format(None)


# --- Tests: _enforce_upperbound_key_params ---


def test_enforce_upperbound_rejects_over_limit_on_generate(monkeypatch):
    """Test that key generation is rejected when values exceed upperbound."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    tpm_limit=1000, rpm_limit=100, max_budget=10.0
                ),
    )
    data = GenerateKeyRequest(tpm_limit=5000)
    with pytest.raises(HTTPException) as exc_info:
        _enforce_upperbound_key_params(data, fill_defaults=True)
    assert exc_info.value.status_code == 400
    assert "tpm_limit" in str(exc_info.value.detail)


def test_enforce_upperbound_fills_defaults_on_generate(monkeypatch):
    """Test that None values are filled with upperbound defaults during generation."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    tpm_limit=1000, rpm_limit=100
                ),
    )
    data = GenerateKeyRequest()  # tpm_limit=None, rpm_limit=None
    _enforce_upperbound_key_params(data, fill_defaults=True)
    assert data.tpm_limit == 1000
    assert data.rpm_limit == 100


def test_enforce_upperbound_skips_none_on_update(monkeypatch):
    """Test that None values are NOT filled during update (fill_defaults=False)."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    tpm_limit=1000, rpm_limit=100
                ),
    )
    data = UpdateKeyRequest(key="sk-test")  # tpm_limit=None, rpm_limit=None
    _enforce_upperbound_key_params(data, fill_defaults=False)
    assert data.tpm_limit is None  # should NOT be filled
    assert data.rpm_limit is None  # should NOT be filled


def test_enforce_upperbound_rejects_over_limit_on_update(monkeypatch):
    """Test that key update is rejected when values exceed upperbound."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    tpm_limit=1000, rpm_limit=100, max_budget=10.0
                ),
    )
    data = UpdateKeyRequest(key="sk-test", tpm_limit=5000)
    with pytest.raises(HTTPException) as exc_info:
        _enforce_upperbound_key_params(data, fill_defaults=False)
    assert exc_info.value.status_code == 400
    assert "tpm_limit" in str(exc_info.value.detail)


def test_enforce_upperbound_allows_within_limit_on_update(monkeypatch):
    """Test that key update passes when values are within upperbound."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    tpm_limit=1000, rpm_limit=100, max_budget=10.0
                ),
    )
    data = UpdateKeyRequest(
        key="sk-test", tpm_limit=500, rpm_limit=50, max_budget=5.0
    )
    _enforce_upperbound_key_params(data, fill_defaults=False)
    # Should not raise
    assert data.tpm_limit == 500
    assert data.rpm_limit == 50
    assert data.max_budget == 5.0


def test_enforce_upperbound_duration_over_limit(monkeypatch):
    """Test that duration exceeding upperbound is rejected."""
    import litellm
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    duration="7d"
                ),
    )
    data = UpdateKeyRequest(key="sk-test", duration="30d")
    with pytest.raises(HTTPException) as exc_info:
        _enforce_upperbound_key_params(data, fill_defaults=False)
    assert exc_info.value.status_code == 400
    assert "duration" in str(exc_info.value.detail)


def test_enforce_upperbound_no_config_is_noop(monkeypatch):
    """Test that no enforcement happens when upperbound params are not configured."""
    import litellm

    monkeypatch.setattr(litellm, "upperbound_key_generate_params", None)
    data = UpdateKeyRequest(key="sk-test", tpm_limit=999999)
    _enforce_upperbound_key_params(data, fill_defaults=False)
    # Should not raise — no enforcement configured
    assert data.tpm_limit == 999999


# --- Tests: _execute_virtual_key_regeneration enforces upperbound ---


def _make_regenerate_mock_prisma():
    """Mock prisma client shaped for _execute_virtual_key_regeneration."""

    class DictLikeResult:
        def __init__(self, data):
            self._data = data

        def __iter__(self):
            return iter(self._data.items())

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=DictLikeResult(
            {
                "token": "new-hashed-token",
                "key_name": "sk-...ab12",
                "user_id": "user-1",
            }
        )
    )
    mock_prisma_client.db.litellm_verificationtoken.create = AsyncMock(
        return_value=None
    )
    mock_prisma_client.jsonify_object = MagicMock(side_effect=lambda data: data)
    return mock_prisma_client


def _make_regenerate_user_api_key_dict():
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin-user",
    )


def _make_regenerate_existing_key():
    return LiteLLM_VerificationToken(
        token="abc123",
        user_id="user-1",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
        tags=None,
    )


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_rejects_over_limit_duration(monkeypatch):
    """Regenerate must reject durations exceeding upperbound_key_generate_params.duration."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    duration="1h"
                ),
    )
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(duration="2h")
    user_api_key_dict = _make_regenerate_user_api_key_dict()
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: archival path is outside upperbound rejection
            "litellm.proxy.management_endpoints.key_management_endpoints.persist_deleted_verification_tokens",
            new_callable=AsyncMock,
        ) as persist_deleted_verification_tokens,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
    ):
        with pytest.raises(HTTPException) as exc_info:
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=existing_key,
                hashed_api_key="abc123",
                key="abc123",
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                user_api_key_cache=MagicMock(),
                proxy_logging_obj=MagicMock(),
            )
    assert exc_info.value.status_code == 400
    assert "duration" in str(exc_info.value.detail)
    # Rejected regenerate must not reach the DB update.
    persist_deleted_verification_tokens.assert_not_awaited()
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_changed_alias_must_match_key_alias_pattern(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    monkeypatch.setattr(litellm, "key_alias_pattern", r"^[a-z0-9]+(-[a-z0-9]+)*$")
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.persist_deleted_verification_tokens",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
    ):
        with pytest.raises(ProxyException) as exc_info:
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=_make_regenerate_existing_key(),
                hashed_api_key="abc123",
                key="abc123",
                data=RegenerateKeyRequest(key_alias="Regenerated Key"),
                user_api_key_dict=_make_regenerate_user_api_key_dict(),
                litellm_changed_by=None,
                user_api_key_cache=MagicMock(),
                proxy_logging_obj=MagicMock(),
            )
    assert str(exc_info.value.code) == "400"
    assert exc_info.value.param == "key_alias"
    assert r"^[a-z0-9]+(-[a-z0-9]+)*$" in str(exc_info.value.message)
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_allows_within_limit_duration(monkeypatch):
    """Regenerate must accept durations within upperbound_key_generate_params.duration."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    duration="1h"
                ),
    )
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(duration="30m")
    user_api_key_dict = _make_regenerate_user_api_key_dict()
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_rejects_when_custom_key_update_hook_denies():
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(duration="3000d")
    mock_prisma_client = _make_regenerate_mock_prisma()
    received_data: list[UpdateKeyRequest] = []

    async def hook(data: UpdateKeyRequest) -> dict[str, object]:
        received_data.append(data)
        if data.duration and duration_in_seconds(data.duration) > duration_in_seconds("7d"):
            return {"decision": False, "message": "duration must be <= 7d"}
        return {"decision": True}

    with (
        patch(  # test-quality-ok: deterministic token setup for policy rejection
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(  # test-quality-ok: grace-period path is outside policy rejection
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ) as insert_deprecated_key,
        patch(  # test-quality-ok: archival path is outside policy rejection
            "litellm.proxy.management_endpoints.key_management_endpoints.persist_deleted_verification_tokens",
            new_callable=AsyncMock,
        ) as persist_deleted_verification_tokens,
        patch(  # test-quality-ok: cache eviction is outside policy rejection
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: rotation callback is outside policy rejection
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.proxy_server.user_custom_key_update", hook),  # test-quality-ok: inject policy hook
    ):
        with pytest.raises(HTTPException) as exc_info:
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=existing_key,
                hashed_api_key="abc123",
                key="abc123",
                data=data,
                user_api_key_dict=_make_regenerate_user_api_key_dict(),
                litellm_changed_by=None,
                user_api_key_cache=MagicMock(),
                proxy_logging_obj=MagicMock(),
            )

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == "duration must be <= 7d"
    insert_deprecated_key.assert_not_awaited()
    persist_deleted_verification_tokens.assert_not_awaited()
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0
    assert len(received_data) == 1
    assert received_data[0].key == "abc123"
    assert received_data[0].duration == "3000d"


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_allows_when_custom_key_update_hook_approves():
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(duration="5d")
    mock_prisma_client = _make_regenerate_mock_prisma()
    received_data: list[UpdateKeyRequest] = []

    async def hook(data: UpdateKeyRequest) -> dict[str, object]:
        received_data.append(data)
        if data.duration and duration_in_seconds(data.duration) > duration_in_seconds("7d"):
            return {"decision": False, "message": "duration must be <= 7d"}
        return {"decision": True}

    with (
        patch(  # test-quality-ok: deterministic token setup for policy approval
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(  # test-quality-ok: grace-period path is outside policy approval
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: verify archival follows policy approval
            "litellm.proxy.management_endpoints.key_management_endpoints.persist_deleted_verification_tokens",
            new_callable=AsyncMock,
        ) as persist_deleted_verification_tokens,
        patch(  # test-quality-ok: cache eviction is outside policy approval
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: rotation callback is outside policy approval
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.proxy_server.user_custom_key_update", hook),  # test-quality-ok: inject policy hook
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1
    persist_deleted_verification_tokens.assert_awaited_once()
    assert persist_deleted_verification_tokens.call_args.kwargs["keys"] == [existing_key]
    assert len(received_data) == 1


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "data",
    [None, RegenerateKeyRequest(), RegenerateKeyRequest(duration=""), RegenerateKeyRequest(budget_duration="")],
)
async def test_execute_virtual_key_regeneration_skips_custom_key_update_hook_without_changes(data):
    mock_prisma_client = _make_regenerate_mock_prisma()

    async def hook(data: UpdateKeyRequest) -> dict[str, object]:
        raise AssertionError(f"custom key update hook called with {data}")

    with (
        patch(  # test-quality-ok: deterministic token setup for unchanged request
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(  # test-quality-ok: grace-period path is outside unchanged request
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: cache eviction is outside unchanged request
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: rotation callback is outside unchanged request
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.proxy_server.user_custom_key_update", hook),  # test-quality-ok: inject policy hook
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=_make_regenerate_existing_key(),
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_hides_the_untouched_modal_expiry_from_the_custom_key_update_hook():
    mock_prisma_client = _make_regenerate_mock_prisma()
    untouched_modal_body = RegenerateKeyRequest(
        key_alias=None, max_budget=None, tpm_limit=None, rpm_limit=None, duration="", grace_period=""
    )
    received_data: list[UpdateKeyRequest] = []

    async def hook(data: UpdateKeyRequest) -> dict[str, object]:
        received_data.append(data)
        if data.duration is not None and duration_in_seconds(data.duration) > duration_in_seconds("7d"):
            return {"decision": False, "message": "duration must be <= 7d"}
        return {"decision": True}

    with (
        patch(  # test-quality-ok: deterministic token setup for the untouched modal body
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(  # test-quality-ok: grace-period path is outside the hook input
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: cache eviction is outside the hook input
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: rotation callback is outside the hook input
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.proxy_server.user_custom_key_update", hook),  # test-quality-ok: inject policy hook
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=_make_regenerate_existing_key(),
            hashed_api_key="abc123",
            key="abc123",
            data=untouched_modal_body,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1
    assert len(received_data) == 1
    assert "duration" not in received_data[0].model_fields_set
    assert received_data[0].model_fields_set >= {"key", "key_alias", "max_budget", "tpm_limit", "rpm_limit"}


_POLICY_DENIAL_MESSAGE = "key duration must be 7d or less"
_POLICY_HASHED_TOKEN = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"
_POLICY_GENERATED_KEY = {"key": "sk-test-key", "expires": None, "user_id": "test-user", "team_id": None}
_OBJECT_PERMISSION_ID_AFTER_POLICY = "perm-after-policy"


def _seven_day_policy(received: list[CustomKeyPolicyRequest]):
    async def policy(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        received.append(policy_request)
        expires = policy_request.effective_key.expires
        if isinstance(expires, datetime) and expires > datetime.now(timezone.utc) + timedelta(days=7):
            return {"decision": False, "message": _POLICY_DENIAL_MESSAGE}
        return {"decision": True}

    return policy


def _assert_expires_in(effective_key: LiteLLM_VerificationToken, duration: str) -> None:
    expires = effective_key.expires
    assert isinstance(expires, datetime)
    assert expires.tzinfo is not None
    expected = datetime.now(timezone.utc) + timedelta(seconds=duration_in_seconds(duration=duration))
    assert abs((expires - expected).total_seconds()) < 60


def _regenerate_policy_mocks(policy, insert_deprecated_key: AsyncMock, persist: AsyncMock) -> ExitStack:
    stack = ExitStack()
    stack.enter_context(
        patch(  # test-quality-ok: deterministic token setup for the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        )
    )
    stack.enter_context(
        patch(  # test-quality-ok: grace-period write must not run on a denied regenerate
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            insert_deprecated_key,
        )
    )
    stack.enter_context(
        patch(  # test-quality-ok: archival write must not run on a denied regenerate
            "litellm.proxy.management_endpoints.key_management_endpoints.persist_deleted_verification_tokens",
            persist,
        )
    )
    stack.enter_context(
        patch(  # test-quality-ok: cache eviction is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        )
    )
    stack.enter_context(
        patch(  # test-quality-ok: rotation callback is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        )
    )
    stack.enter_context(
        patch("litellm.proxy.proxy_server.user_custom_key_policy", policy)  # test-quality-ok: inject policy hook
    )
    return stack


async def _regenerate_under_policy(mock_prisma_client, existing_key, data):
    return await _execute_virtual_key_regeneration(
        prisma_client=mock_prisma_client,
        key_in_db=existing_key,
        hashed_api_key="abc123",
        key="abc123",
        data=data,
        user_api_key_dict=_make_regenerate_user_api_key_dict(),
        litellm_changed_by=None,
        user_api_key_cache=MagicMock(),
        proxy_logging_obj=MagicMock(),
    )


@pytest.mark.asyncio
async def test_regenerate_rejects_when_custom_key_policy_denies_the_effective_expiry():
    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = _make_regenerate_mock_prisma()
    received: list[CustomKeyPolicyRequest] = []
    insert_deprecated_key = AsyncMock()
    persist = AsyncMock()

    with _regenerate_policy_mocks(_seven_day_policy(received), insert_deprecated_key, persist):
        with pytest.raises(HTTPException) as exc_info:
            await _regenerate_under_policy(mock_prisma_client, existing_key, RegenerateKeyRequest(duration="3000d"))

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == _POLICY_DENIAL_MESSAGE
    insert_deprecated_key.assert_not_awaited()
    persist.assert_not_awaited()
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0
    assert [policy_request.operation for policy_request in received] == ["regenerate"]
    assert received[0].existing_key is not None
    assert received[0].existing_key.token == "abc123"
    assert isinstance(received[0].request, RegenerateKeyRequest)
    assert received[0].request.duration == "3000d"
    _assert_expires_in(received[0].effective_key, "3000d")


@pytest.mark.asyncio
async def test_regenerate_within_custom_key_policy_rotates_the_key():
    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = _make_regenerate_mock_prisma()
    received: list[CustomKeyPolicyRequest] = []
    persist = AsyncMock()

    with _regenerate_policy_mocks(_seven_day_policy(received), AsyncMock(), persist):
        await _regenerate_under_policy(mock_prisma_client, existing_key, RegenerateKeyRequest(duration="5d"))

    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1
    persist.assert_awaited_once()
    assert persist.call_args.kwargs["keys"] == [existing_key]
    assert [policy_request.operation for policy_request in received] == ["regenerate"]
    _assert_expires_in(received[0].effective_key, "5d")


@pytest.mark.asyncio
@pytest.mark.parametrize("data", [None, RegenerateKeyRequest()])
async def test_regenerate_without_changes_still_runs_custom_key_policy(data):
    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = _make_regenerate_mock_prisma()
    received: list[CustomKeyPolicyRequest] = []

    async def freeze_rotation(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        received.append(policy_request)
        return {"decision": False, "message": "key rotation is frozen"}

    with _regenerate_policy_mocks(freeze_rotation, AsyncMock(), AsyncMock()):
        with pytest.raises(HTTPException) as exc_info:
            await _regenerate_under_policy(mock_prisma_client, existing_key, data)

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == "key rotation is frozen"
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0
    assert [policy_request.operation for policy_request in received] == ["regenerate"]
    assert received[0].existing_key == existing_key
    assert received[0].effective_key == existing_key


def _policy_existing_team_key() -> LiteLLM_VerificationToken:
    return LiteLLM_VerificationToken(
        token=_POLICY_HASHED_TOKEN,
        user_id="test-user",
        team_id="team-a",
        max_budget=200.0,
        object_permission_id=_OBJECT_PERMISSION_ID_AFTER_POLICY,
    )


def _setup_update_key_fn_policy_mocks(monkeypatch, existing_key: LiteLLM_VerificationToken) -> AsyncMock:
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing_key)
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(return_value=None)
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {"max_budget": 50.0, "team_id": "team-a"}})
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", AsyncMock(return_value=None)
    )
    return mock_prisma_client


def _assert_update_policy_request(policy_request: CustomKeyPolicyRequest, request: UpdateKeyRequest) -> None:
    assert policy_request.operation == "update"
    assert policy_request.request is request
    assert policy_request.existing_key is not None
    assert policy_request.existing_key.max_budget == 200.0
    assert policy_request.effective_key.team_id == "team-a"
    assert policy_request.effective_key.user_id == "test-user"
    assert policy_request.effective_key.max_budget == 50.0
    _assert_expires_in(policy_request.effective_key, request.duration or "")


@pytest.mark.asyncio
async def test_update_key_fn_runs_custom_key_policy_on_the_effective_row(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import update_key_fn

    mock_prisma_client = _setup_update_key_fn_policy_mocks(monkeypatch, _policy_existing_team_key())
    received: list[CustomKeyPolicyRequest] = []
    policy = _seven_day_policy(received)
    data = UpdateKeyRequest(
        key=_POLICY_HASHED_TOKEN, duration="5d", max_budget=50.0, auto_rotate=True, rotation_interval="30d"
    )

    with (
        patch(  # test-quality-ok: cache eviction is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.proxy_server.user_custom_key_policy", policy),  # test-quality-ok: inject policy hook
    ):
        await update_key_fn(
            request=MagicMock(),
            data=data,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
        )

    mock_prisma_client.update_data.assert_awaited_once()
    assert len(received) == 1
    _assert_update_policy_request(received[0], data)
    key_rotation_at = received[0].effective_key.key_rotation_at
    assert key_rotation_at is not None
    assert abs(key_rotation_at - (datetime.now(timezone.utc) + timedelta(days=30))) < timedelta(seconds=60)


@pytest.mark.asyncio
async def test_update_key_fn_rejects_when_custom_key_policy_denies(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import update_key_fn

    mock_prisma_client = _setup_update_key_fn_policy_mocks(monkeypatch, _policy_existing_team_key())
    received: list[CustomKeyPolicyRequest] = []
    policy = _seven_day_policy(received)

    with patch("litellm.proxy.proxy_server.user_custom_key_policy", policy):  # test-quality-ok: inject policy hook
        with pytest.raises(ProxyException) as exc_info:
            await update_key_fn(
                request=MagicMock(),
                data=UpdateKeyRequest(key=_POLICY_HASHED_TOKEN, duration="3000d", max_budget=50.0),
                user_api_key_dict=_make_regenerate_user_api_key_dict(),
                litellm_changed_by=None,
            )

    assert str(exc_info.value.code) == "403"
    assert exc_info.value.message == _POLICY_DENIAL_MESSAGE
    mock_prisma_client.update_data.assert_not_awaited()
    assert [policy_request.operation for policy_request in received] == ["update"]
    _assert_expires_in(received[0].effective_key, "3000d")


async def _process_single_key_update_under_policy(prisma_client: AsyncMock, data: UpdateKeyRequest, policy):
    with (
        patch(  # test-quality-ok: cache eviction is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: update callback is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: the existing key's team is outside the policy path, as in the /key/update tests
            "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
            new_callable=AsyncMock,
            return_value=None,
        ),
    ):
        return await _process_single_key_update(
            update_key_request=data,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            prisma_client=prisma_client,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=None,
            existing_key_row=_policy_existing_team_key(),
            user_custom_key_policy=policy,
        )


@pytest.mark.asyncio
async def test_process_single_key_update_runs_custom_key_policy_on_the_effective_row():
    mock_prisma_client = AsyncMock()
    updated_row = MagicMock()
    updated_row.model_dump.return_value = {"max_budget": 50.0, "team_id": "team-a"}
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_row})
    received: list[CustomKeyPolicyRequest] = []
    data = UpdateKeyRequest(key=_POLICY_HASHED_TOKEN, duration="5d", max_budget=50.0)

    result = await _process_single_key_update_under_policy(mock_prisma_client, data, _seven_day_policy(received))

    assert result["max_budget"] == 50.0
    mock_prisma_client.update_data.assert_awaited_once()
    assert len(received) == 1
    _assert_update_policy_request(received[0], data)


@pytest.mark.asyncio
async def test_process_single_key_update_rejects_when_custom_key_policy_denies():
    mock_prisma_client = AsyncMock()
    mock_prisma_client.update_data = AsyncMock()
    received: list[CustomKeyPolicyRequest] = []
    data = UpdateKeyRequest(key=_POLICY_HASHED_TOKEN, duration="3000d", max_budget=50.0)

    with pytest.raises(HTTPException) as exc_info:
        await _process_single_key_update_under_policy(mock_prisma_client, data, _seven_day_policy(received))

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == _POLICY_DENIAL_MESSAGE
    mock_prisma_client.update_data.assert_not_awaited()
    assert [policy_request.operation for policy_request in received] == ["update"]


def _record_object_permission_writes(mock_prisma_client: AsyncMock, events: list[str]) -> None:
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=None)

    async def upsert(**_kwargs: object) -> MagicMock:
        events.append("permission row upsert")
        return MagicMock(object_permission_id=_OBJECT_PERMISSION_ID_AFTER_POLICY)

    mock_prisma_client.db.litellm_objectpermissiontable.upsert = AsyncMock(side_effect=upsert)


def _recording_policy(events: list[str], allowed: bool):
    async def policy(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        events.append("policy")
        return {"decision": allowed, "message": "key max_budget must be 1000 or less"}

    return policy


def _assert_permission_row_written_after_policy(events: list[str], written: Mapping[str, object]) -> None:
    assert events == ["policy", "permission row upsert"]
    assert written["object_permission_id"] == _OBJECT_PERMISSION_ID_AFTER_POLICY
    assert "object_permission" not in written


def _assert_permission_row_untouched(mock_prisma_client: AsyncMock, events: list[str]) -> None:
    assert events == ["policy"]
    mock_prisma_client.db.litellm_objectpermissiontable.upsert.assert_not_awaited()


def _update_with_object_permission(max_budget: float) -> UpdateKeyRequest:
    return UpdateKeyRequest(
        key=_POLICY_HASHED_TOKEN,
        max_budget=max_budget,
        object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["vs-1"]),
    )


def _setup_update_key_fn_object_permission_mocks(monkeypatch, allowed: bool) -> tuple[AsyncMock, list[str]]:
    mock_prisma_client = _setup_update_key_fn_policy_mocks(monkeypatch, _policy_existing_team_key())
    events: list[str] = []
    _record_object_permission_writes(mock_prisma_client, events)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_custom_key_policy", _recording_policy(events, allowed))
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object", AsyncMock()
    )
    return mock_prisma_client, events


async def _update_key_fn_with_object_permission(max_budget: float):
    from litellm.proxy.management_endpoints.key_management_endpoints import update_key_fn

    return await update_key_fn(
        request=MagicMock(),
        data=_update_with_object_permission(max_budget=max_budget),
        user_api_key_dict=_make_regenerate_user_api_key_dict(),
        litellm_changed_by=None,
    )


@pytest.mark.asyncio
async def test_update_key_fn_writes_the_object_permission_row_only_after_the_policy_allows(monkeypatch):
    mock_prisma_client, events = _setup_update_key_fn_object_permission_mocks(monkeypatch, allowed=True)

    await _update_key_fn_with_object_permission(max_budget=50.0)

    _assert_permission_row_written_after_policy(events, mock_prisma_client.update_data.await_args.kwargs["data"])


@pytest.mark.asyncio
async def test_update_key_fn_denied_by_the_policy_leaves_the_object_permission_row_untouched(monkeypatch):
    mock_prisma_client, events = _setup_update_key_fn_object_permission_mocks(monkeypatch, allowed=False)

    with pytest.raises(ProxyException) as exc_info:
        await _update_key_fn_with_object_permission(max_budget=5000.0)

    assert str(exc_info.value.code) == "403"
    _assert_permission_row_untouched(mock_prisma_client, events)
    mock_prisma_client.update_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_process_single_key_update_writes_the_object_permission_row_only_after_the_policy_allows():
    mock_prisma_client = AsyncMock()
    updated_row = MagicMock()
    updated_row.model_dump.return_value = {"max_budget": 50.0, "team_id": "team-a"}
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_row})
    events: list[str] = []
    _record_object_permission_writes(mock_prisma_client, events)

    await _process_single_key_update_under_policy(
        mock_prisma_client, _update_with_object_permission(max_budget=50.0), _recording_policy(events, allowed=True)
    )

    _assert_permission_row_written_after_policy(events, mock_prisma_client.update_data.await_args.kwargs["data"])


@pytest.mark.asyncio
async def test_process_single_key_update_denied_by_the_policy_leaves_the_object_permission_row_untouched():
    mock_prisma_client = AsyncMock()
    mock_prisma_client.update_data = AsyncMock()
    events: list[str] = []
    _record_object_permission_writes(mock_prisma_client, events)

    with pytest.raises(HTTPException) as exc_info:
        await _process_single_key_update_under_policy(
            mock_prisma_client, _update_with_object_permission(max_budget=5000.0), _recording_policy(events, allowed=False)
        )

    assert exc_info.value.status_code == 403
    _assert_permission_row_untouched(mock_prisma_client, events)
    mock_prisma_client.update_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_regenerate_writes_the_object_permission_row_only_after_the_policy_allows():
    mock_prisma_client = _make_regenerate_mock_prisma()
    events: list[str] = []
    _record_object_permission_writes(mock_prisma_client, events)
    data = RegenerateKeyRequest(max_budget=50.0, object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["vs-1"]))
    existing_key: Final = _make_regenerate_existing_key().model_copy(
        update={"object_permission_id": _OBJECT_PERMISSION_ID_AFTER_POLICY}
    )

    with _regenerate_policy_mocks(_recording_policy(events, allowed=True), AsyncMock(), AsyncMock()):
        await _regenerate_under_policy(mock_prisma_client, existing_key, data)

    _assert_permission_row_written_after_policy(
        events, mock_prisma_client.db.litellm_verificationtoken.update.await_args.kwargs["data"]
    )


@pytest.mark.asyncio
async def test_regenerate_denied_by_the_policy_leaves_the_object_permission_row_untouched():
    mock_prisma_client = _make_regenerate_mock_prisma()
    events: list[str] = []
    _record_object_permission_writes(mock_prisma_client, events)
    data = RegenerateKeyRequest(max_budget=5000.0, object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["vs-1"]))

    with _regenerate_policy_mocks(_recording_policy(events, allowed=False), AsyncMock(), AsyncMock()):
        with pytest.raises(HTTPException) as exc_info:
            await _regenerate_under_policy(mock_prisma_client, _make_regenerate_existing_key(), data)

    assert exc_info.value.status_code == 403
    _assert_permission_row_untouched(mock_prisma_client, events)
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0


@pytest.mark.asyncio
async def test_bulk_update_keys_runs_custom_key_policy_per_key(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import bulk_update_keys
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateKeyRequest,
        BulkUpdateKeyRequestItem,
    )

    existing_keys = [
        LiteLLM_VerificationToken(token="test-key-1", user_id="user-123", max_budget=None),
        LiteLLM_VerificationToken(token="test-key-2", user_id="user-123", max_budget=50.0),
    ]
    updated_row = MagicMock()
    updated_row.model_dump.return_value = {"user_id": "user-123", "max_budget": 100.0}
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(side_effect=existing_keys)
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_row})
    mock_prisma_client.get_data = AsyncMock(return_value=None)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    received: list[CustomKeyPolicyRequest] = []

    async def cap_max_budget(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        received.append(policy_request)
        max_budget = policy_request.effective_key.max_budget
        if max_budget is not None and max_budget > 100:
            return {"decision": False, "message": "max_budget must be 100 or less"}
        return {"decision": True}

    monkeypatch.setattr("litellm.proxy.proxy_server.user_custom_key_policy", cap_max_budget)

    with (
        patch(  # test-quality-ok: cache eviction is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: update callback is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook",
            new_callable=AsyncMock,
        ),
    ):
        response = await bulk_update_keys(
            data=BulkUpdateKeyRequest(
                keys=[
                    BulkUpdateKeyRequestItem(key="test-key-1", max_budget=100.0),
                    BulkUpdateKeyRequestItem(key="test-key-2", max_budget=500.0),
                ]
            ),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
        )

    assert [update.key for update in response.successful_updates] == ["test-key-1"]
    assert [(failed.key, failed.failed_reason) for failed in response.failed_updates] == [
        ("test-key-2", "max_budget must be 100 or less")
    ]
    assert mock_prisma_client.update_data.await_count == 1
    assert [policy_request.operation for policy_request in received] == ["update", "update"]
    assert [policy_request.effective_key.max_budget for policy_request in received] == [100.0, 500.0]
    assert [
        policy_request.existing_key.max_budget if policy_request.existing_key is not None else "missing"
        for policy_request in received
    ] == [None, 50.0]


def _policy_generate_prisma() -> MagicMock:
    mock_prisma = MagicMock()
    mock_prisma.db.litellm_budgettable.create = AsyncMock(return_value=MagicMock(budget_id="budget-1"))
    mock_prisma.jsonify_object = MagicMock(side_effect=lambda data: json.loads(data) if isinstance(data, str) else data)
    return mock_prisma


def _generate_policy_mocks(mock_prisma: MagicMock, generate_key_helper: AsyncMock, policy) -> ExitStack:
    stack = ExitStack()
    stack.enter_context(patch("litellm.proxy.proxy_server.prisma_client", mock_prisma))  # test-quality-ok: fake DB
    stack.enter_context(patch("litellm.proxy.proxy_server.llm_router", None))  # test-quality-ok: no router in test
    stack.enter_context(patch("litellm.proxy.proxy_server.premium_user", True))  # test-quality-ok: premium fields
    stack.enter_context(patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"))  # test-quality-ok: admin
    stack.enter_context(patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()))  # test-quality-ok: cache
    stack.enter_context(
        patch(  # test-quality-ok: the key write must not run on a denied generate
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            generate_key_helper,
        )
    )
    stack.enter_context(
        patch("litellm.proxy.proxy_server.user_custom_key_policy", policy)  # test-quality-ok: inject policy hook
    )
    return stack


def _generate_request(duration: str, organization_id: str | None) -> GenerateKeyRequest:
    return GenerateKeyRequest(
        duration=duration,
        organization_id=organization_id,
        guardrails=["g1"],
        tags=["t1"],
        soft_budget=10.0,
        max_budget=20.0,
    )


def _assert_generate_policy_request(
    policy_request: CustomKeyPolicyRequest, duration: str, organization_id: str | None
) -> None:
    assert policy_request.operation == "generate"
    assert policy_request.existing_key is None
    assert policy_request.effective_key.org_id == organization_id
    assert policy_request.effective_key.max_budget == 20.0
    assert policy_request.effective_key.metadata["guardrails"] == ["g1"]
    assert policy_request.effective_key.metadata["tags"] == ["t1"]
    _assert_expires_in(policy_request.effective_key, duration)


@pytest.mark.asyncio
async def test_generate_key_rejects_when_custom_key_policy_denies_before_any_write():
    mock_prisma = _policy_generate_prisma()
    generate_key_helper = AsyncMock(return_value=_POLICY_GENERATED_KEY)
    received: list[CustomKeyPolicyRequest] = []
    data = _generate_request("3000d", organization_id="org-1")

    with _generate_policy_mocks(mock_prisma, generate_key_helper, _seven_day_policy(received)):
        with pytest.raises(ProxyException) as exc_info:
            await generate_key_fn(
                data=data, user_api_key_dict=_make_regenerate_user_api_key_dict(), litellm_changed_by=None
            )

    assert str(exc_info.value.code) == "403"
    assert exc_info.value.message == _POLICY_DENIAL_MESSAGE
    mock_prisma.db.litellm_budgettable.create.assert_not_awaited()
    generate_key_helper.assert_not_awaited()
    assert len(received) == 1
    _assert_generate_policy_request(received[0], "3000d", organization_id="org-1")
    assert received[0].request is data
    assert data.duration == "3000d"
    assert data.guardrails == ["g1"]
    assert data.tags == ["t1"]
    assert data.organization_id == "org-1"


@pytest.mark.asyncio
async def test_generate_key_within_custom_key_policy_creates_the_key():
    mock_prisma = _policy_generate_prisma()
    generate_key_helper = AsyncMock(return_value=_POLICY_GENERATED_KEY)
    received: list[CustomKeyPolicyRequest] = []
    data = _generate_request("5d", organization_id=None)

    with _generate_policy_mocks(mock_prisma, generate_key_helper, _seven_day_policy(received)):
        await generate_key_fn(
            data=data, user_api_key_dict=_make_regenerate_user_api_key_dict(), litellm_changed_by=None
        )

    mock_prisma.db.litellm_budgettable.create.assert_awaited_once()
    generate_key_helper.assert_awaited_once()
    assert len(received) == 1
    _assert_generate_policy_request(received[0], "5d", organization_id=None)
    assert received[0].request is data


@pytest.mark.asyncio
async def test_service_account_generate_rejects_when_custom_key_policy_denies():
    from litellm.proxy.management_endpoints.key_management_endpoints import generate_service_account_key_fn

    mock_prisma = _policy_generate_prisma()
    mock_prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=MagicMock())
    generate_key_helper = AsyncMock(return_value=_POLICY_GENERATED_KEY)
    received: list[CustomKeyPolicyRequest] = []

    with (
        _generate_policy_mocks(mock_prisma, generate_key_helper, _seven_day_policy(received)),
        patch(  # test-quality-ok: team lookup is outside the policy path
            "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
            new_callable=AsyncMock,
            return_value=None,
        ),
    ):
        with pytest.raises(HTTPException) as exc_info:
            await generate_service_account_key_fn(
                data=GenerateKeyRequest(team_id="team-1", duration="3000d"),
                user_api_key_dict=_make_regenerate_user_api_key_dict(),
                litellm_changed_by=None,
            )

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == _POLICY_DENIAL_MESSAGE
    generate_key_helper.assert_not_awaited()
    mock_prisma.db.litellm_budgettable.create.assert_not_awaited()
    assert [policy_request.operation for policy_request in received] == ["generate"]
    assert received[0].existing_key is None
    assert received[0].effective_key.team_id == "team-1"
    assert received[0].effective_key.user_id is None
    _assert_expires_in(received[0].effective_key, "3000d")


@pytest.mark.asyncio
async def test_effective_key_after_update_decodes_json_string_columns_and_keeps_omitted_fields():
    existing_key = LiteLLM_VerificationToken(token="tok", user_id="u1", team_id="team-a")
    non_default_values = await prepare_key_update_data(
        data=UpdateKeyRequest(
            key="tok", router_settings={"num_retries": 3}, budget_limits=[{"budget_duration": "1d", "max_budget": 2.0}]
        ),
        existing_key_row=existing_key,
    )
    assert isinstance(non_default_values["router_settings"], str)
    assert isinstance(non_default_values["budget_limits"], str)

    effective_key = _effective_key_after_update(existing_key_row=existing_key, non_default_values=non_default_values)

    assert effective_key.router_settings == {"num_retries": 3}
    assert effective_key.budget_limits is not None
    assert effective_key.budget_limits[0]["max_budget"] == 2.0
    assert effective_key.budget_limits[0]["budget_duration"] == "1d"
    assert effective_key.budget_limits[0]["reset_at"] is not None
    assert effective_key.team_id == "team-a"
    assert effective_key.user_id == "u1"


@pytest.mark.asyncio
async def test_effective_key_after_update_clears_expiry_for_a_minus_one_duration():
    existing_key = LiteLLM_VerificationToken(token="tok", expires=datetime(2027, 1, 1, tzinfo=timezone.utc))
    non_default_values = await prepare_key_update_data(
        data=UpdateKeyRequest(key="tok", duration="-1"), existing_key_row=existing_key
    )

    effective_key = _effective_key_after_update(existing_key_row=existing_key, non_default_values=non_default_values)

    assert effective_key.expires is None


def test_effective_key_after_update_swaps_the_object_permission_id_and_drops_the_stale_relation():
    existing_key = LiteLLM_VerificationToken(
        token="tok",
        object_permission_id="op-old",
        object_permission=LiteLLM_ObjectPermissionTable(object_permission_id="op-old", mcp_servers=["old"]),
    )

    effective_key = _effective_key_after_update(
        existing_key_row=existing_key, non_default_values={"object_permission_id": "op-new"}
    )

    assert effective_key.object_permission_id == "op-new"
    assert effective_key.object_permission is None
    assert existing_key.object_permission is not None
    assert existing_key.object_permission.mcp_servers == ["old"]


def test_effective_key_for_generate_reflects_the_processed_request_without_mutating_it():
    now = datetime(2026, 1, 1, tzinfo=timezone.utc)
    data = GenerateKeyRequest(
        duration="5d",
        organization_id="org-1",
        metadata={"a": 1},
        guardrails=["g1"],
        tags=["t1"],
        budget_duration="1d",
        max_budget=3.0,
        budget_limits=[{"budget_duration": "1d", "max_budget": 5.0}],
        auto_rotate=True,
        rotation_interval="30d",
        object_permission={"mcp_servers": ["srv"]},
        key_type=LiteLLMKeyType.LLM_API,
    )

    effective_key = _effective_key_for_generate(data=data, now=now)

    assert effective_key.expires == now + timedelta(days=5)
    assert effective_key.key_rotation_at == now + timedelta(days=30)
    assert effective_key.budget_limits is not None
    assert effective_key.budget_limits[0]["max_budget"] == 5.0
    assert effective_key.budget_limits[0]["reset_at"] is not None
    assert effective_key.object_permission is None
    assert effective_key.org_id == "org-1"
    assert effective_key.metadata == {"a": 1, "guardrails": ["g1"], "tags": ["t1"]}
    assert effective_key.max_budget == 3.0
    assert effective_key.budget_duration == "1d"
    assert effective_key.budget_reset_at is not None
    assert effective_key.key_type == "llm_api"
    assert effective_key.allowed_routes == ["llm_api_routes"]
    assert data.metadata == {"a": 1}
    assert data.guardrails == ["g1"]
    assert data.tags == ["t1"]
    assert data.duration == "5d"
    assert data.budget_limits is not None
    assert data.budget_limits[0].reset_at is None
    assert data.object_permission is not None
    assert data.object_permission.mcp_servers == ["srv"]


def test_effective_key_for_generate_stores_no_budget_windows_for_an_empty_list():
    effective_key = _effective_key_for_generate(
        data=GenerateKeyRequest(budget_limits=[]), now=datetime(2026, 1, 1, tzinfo=timezone.utc)
    )

    assert effective_key.budget_limits is None


def test_effective_key_for_generate_without_duration_never_expires():
    effective_key = _effective_key_for_generate(
        data=GenerateKeyRequest(), now=datetime(2026, 1, 1, tzinfo=timezone.utc)
    )

    assert effective_key.expires is None
    assert effective_key.budget_reset_at is None
    assert effective_key.key_rotation_at is None
    assert effective_key.key_type == "default"


def _policy_request_for_generate() -> CustomKeyPolicyRequest:
    return CustomKeyPolicyRequest(
        operation="generate",
        existing_key=None,
        effective_key=LiteLLM_VerificationToken(token="tok"),
        request=GenerateKeyRequest(),
    )


@pytest.mark.asyncio
async def test_enforce_custom_key_policy_rejects_a_sync_hook():
    def sync_hook(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        return {"decision": True}

    with pytest.raises(ValueError, match="user_custom_key_policy must be a coroutine"):
        await _enforce_custom_key_policy(hook=sync_hook, build_policy_request=_policy_request_for_generate)


@pytest.mark.asyncio
async def test_enforce_custom_key_policy_uses_the_default_denial_message():
    async def deny(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        return {"decision": False}

    with pytest.raises(HTTPException) as exc_info:
        await _enforce_custom_key_policy(hook=deny, build_policy_request=_policy_request_for_generate)

    assert exc_info.value.status_code == 403
    assert exc_info.value.detail == "Authentication Failed - Custom Auth Rule"


@pytest.mark.asyncio
async def test_enforce_custom_key_policy_allows_when_the_decision_is_missing():
    received: list[CustomKeyPolicyRequest] = []

    async def no_decision(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        received.append(policy_request)
        return {}

    await _enforce_custom_key_policy(hook=no_decision, build_policy_request=_policy_request_for_generate)

    assert len(received) == 1
    assert received[0].operation == "generate"


@pytest.mark.asyncio
async def test_enforce_custom_key_policy_never_builds_the_request_without_a_hook():
    await _enforce_custom_key_policy(
        hook=None, build_policy_request=lambda: pytest.fail("policy request built without a hook")
    )


@pytest.mark.asyncio
async def test_regenerate_evicts_jwt_key_mapping_cache_so_next_jwt_call_gets_new_token():
    """
    LIT-5379: /key/regenerate rewrites the JWT mapping row to the new token (FK
    cascade) but left the jwt_key_mapping cache entry pointing at the old hash,
    so JWT calls kept resolving the dead token until the cache TTL expired.
    Regenerate must evict the entry locally, broadcast the eviction to other
    workers, and the very next JWT resolve must return the rotated token.
    """
    from litellm.caching.caching import DualCache
    from litellm.proxy._types import LiteLLM_JWTAuth
    from litellm.proxy.auth.auth_method import AuthMethod
    from litellm.proxy.auth.resolvers.models import CredentialRef
    from litellm.proxy.auth.resolvers.store import IdentityStore
    from litellm.proxy.auth.user_api_key_auth import _resolve_jwt_to_virtual_key
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    stale_cache_key = jwt_key_mapping_cache_key("sub", "user1", None)
    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = _make_regenerate_mock_prisma()
    mock_prisma_client.db.litellm_jwtkeymapping.find_many = AsyncMock(
        return_value=[MagicMock(jwt_claim_name="sub", jwt_claim_value="user1", jwt_issuer=None)]
    )
    mock_prisma_client.db.litellm_jwtkeymapping.find_first = AsyncMock(
        return_value=MagicMock(token="new-hashed-token")
    )
    user_api_key_cache = DualCache()
    await user_api_key_cache.async_set_cache(key=stale_cache_key, value="abc123")

    publish_mock = AsyncMock()
    with (
        patch(  # test-quality-ok: deterministic token; same pattern as sibling regenerate tests
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(  # test-quality-ok: grace-period path not under test; same pattern as sibling regenerate tests
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: key-object eviction is separate from the mapping eviction under test
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: background rotation hook is irrelevant to cache eviction
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch(  # test-quality-ok: captures the cross-worker broadcast without a redis instance
            "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.publish_auth_cache_invalidation",
            publish_mock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=None,
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=user_api_key_cache,
            proxy_logging_obj=MagicMock(),
        )

    assert await user_api_key_cache.async_get_cache(stale_cache_key) is None
    publish_mock.assert_any_await(cache_key=stale_cache_key)
    mock_prisma_client.db.litellm_jwtkeymapping.find_many.assert_awaited_once_with(where={"token": "abc123"})

    rotated_key = UserAPIKeyAuth(token="new-hashed-token", user_id="user-1")
    rotated_principal = IdentityStore._principal_from_key(
        rotated_key,
        auth_method=AuthMethod.API_KEY,
        credential_ref=CredentialRef(token_id="new-hashed-token"),
    )

    async def fake_resolve(hashed_token):
        assert hashed_token == "new-hashed-token", f"JWT resolved stale token {hashed_token!r} after regenerate"
        return rotated_principal

    jwt_handler = MagicMock()
    jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(
        virtual_key_claim_field="sub", virtual_key_mapping_cache_ttl=300
    )
    with patch(  # test-quality-ok: DB-backed resolve; fake asserts it receives the rotated hash
        "litellm.proxy.auth.resolvers.store.IdentityStore.resolve",
        new_callable=AsyncMock,
        side_effect=fake_resolve,
    ):
        resolved = await _resolve_jwt_to_virtual_key(
            jwt_claims={"sub": "user1"},
            jwt_handler=jwt_handler,
            prisma_client=mock_prisma_client,
            user_api_key_cache=user_api_key_cache,
            parent_otel_span=None,
            proxy_logging_obj=MagicMock(),
        )
    assert isinstance(resolved, UserAPIKeyAuth)
    assert resolved.token == "new-hashed-token"


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_rejects_over_limit_max_budget(monkeypatch):
    """Regenerate must reject max_budget exceeding upperbound — proves the fix covers non-duration fields."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    max_budget=10.0
                ),
    )
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(max_budget=500.0)
    user_api_key_dict = _make_regenerate_user_api_key_dict()
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
    ):
        with pytest.raises(HTTPException) as exc_info:
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=existing_key,
                hashed_api_key="abc123",
                key="abc123",
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                user_api_key_cache=MagicMock(),
                proxy_logging_obj=MagicMock(),
            )
    assert exc_info.value.status_code == 400
    assert "max_budget" in str(exc_info.value.detail)
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 0


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_skips_none_values(monkeypatch):
    """Regenerate with data.duration=None must not raise, even when upperbound is set
    (fill_defaults=False semantic — None means 'inherit from existing key')."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(
                    duration="1h"
                ),
    )
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest()  # all fields None
    user_api_key_dict = _make_regenerate_user_api_key_dict()
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_no_upperbound_config_is_noop(monkeypatch):
    """Regenerate with no upperbound config set must accept any duration."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    monkeypatch.setattr(litellm, "upperbound_key_generate_params", None)
    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(duration="30d")
    user_api_key_dict = _make_regenerate_user_api_key_dict()
    mock_prisma_client = _make_regenerate_mock_prisma()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1


class TestAllowedRoutesCallerPermission:
    """
    Non-admins must not be able to set `allowed_routes` on a key. The field
    bypasses the role-based route gate in
    RouteChecks.non_proxy_admin_allowed_routes_check, so allowing a non-admin
    to populate it grants them arbitrary endpoint access.
    """

    @pytest.mark.asyncio
    async def test_non_admin_generate_key_with_allowed_routes_rejected(self):
        data = GenerateKeyRequest(
            key_alias="escalate",
            allowed_routes=["/*"],
        )
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await generate_key_fn(
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_admin_generate_key_with_allowed_routes_allowed(self):
        data = GenerateKeyRequest(
            key_alias="admin-key",
            allowed_routes=["/chat/completions"],
            user_id="admin-user",
        )
        user_api_key_dict = UserAPIKeyAuth(
            user_id="admin-user",
            user_role=LitellmUserRoles.PROXY_ADMIN,
        )
        mock_prisma_client = AsyncMock()
        stub_response = MagicMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=stub_response,
            ),
        ):
            result = await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )
        assert result is stub_response

    @pytest.mark.asyncio
    async def test_non_admin_generate_key_default_empty_allowed_routes_ok(self):
        """
        Regression guard: GenerateKeyRequest.allowed_routes defaults to [], so
        the helper must treat empty-list as "not set" or every non-admin key
        creation breaks.
        """
        data = GenerateKeyRequest(key_alias="plain-key")
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()
        stub_response = MagicMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=stub_response,
            ),
        ):
            result = await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )
        assert result is stub_response

    @pytest.mark.asyncio
    async def test_non_admin_update_key_with_allowed_routes_rejected(self):
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            update_key_fn,
        )

        data = UpdateKeyRequest(key="sk-test", allowed_routes=["/*"])
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_update", None),
            patch("litellm.proxy.proxy_server.llm_router", None),
            patch("litellm.proxy.proxy_server.premium_user", True),
            patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._get_and_validate_existing_key",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await update_key_fn(
                    request=MagicMock(),
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_non_admin_update_key_explicit_empty_allowed_routes_rejected(self):
        """`update_key_fn` rejects a non-admin clearing a custom (non-preset)
        route restriction with an explicit `[]` in the request body. The value
        matches the model default but `model_fields_set` distinguishes the
        two. Clearing from a safe preset is allowed (LIT-4891)."""
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            update_key_fn,
        )

        data = UpdateKeyRequest(key="sk-test", allowed_routes=[])
        assert "allowed_routes" in data.model_fields_set
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_update", None),
            patch("litellm.proxy.proxy_server.llm_router", None),
            patch("litellm.proxy.proxy_server.premium_user", True),
            patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._get_and_validate_existing_key",
                new_callable=AsyncMock,
                return_value=MagicMock(allowed_routes=["/chat/completions"]),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await update_key_fn(
                    request=MagicMock(),
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_non_admin_update_key_explicit_null_allowed_routes_rejected(self):
        """`update_key_fn` rejects a non-admin clearing a custom (non-preset)
        route restriction with an explicit `null` in the request body."""
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            update_key_fn,
        )

        data = UpdateKeyRequest(key="sk-test", allowed_routes=None)
        assert "allowed_routes" in data.model_fields_set
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_update", None),
            patch("litellm.proxy.proxy_server.llm_router", None),
            patch("litellm.proxy.proxy_server.premium_user", True),
            patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._get_and_validate_existing_key",
                new_callable=AsyncMock,
                return_value=MagicMock(allowed_routes=["/chat/completions"]),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await update_key_fn(
                    request=MagicMock(),
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_non_admin_regenerate_key_explicit_empty_allowed_routes_rejected(self):
        """`regenerate_key_fn` rejects a non-admin when `allowed_routes` is
        present as `[]` in the request body."""
        from litellm.proxy._types import RegenerateKeyRequest
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            regenerate_key_fn,
        )

        data = RegenerateKeyRequest(key="sk-test", allowed_routes=[])
        assert "allowed_routes" in data.model_fields_set
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with patch("litellm.proxy.proxy_server.premium_user", True):
            with pytest.raises(ProxyException) as exc_info:
                await regenerate_key_fn(
                    key=None,
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_non_admin_regenerate_key_allowed_routes_rejected_before_enterprise_gate(self):
        """`regenerate_key_fn` runs `_check_allowed_routes_caller_permission`
        before the `premium_user` check, so a non-premium proxy still returns
        the allowed_routes rejection (403) rather than the enterprise-license
        error (500) when a non-admin sends `allowed_routes`."""
        from litellm.proxy._types import RegenerateKeyRequest
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            regenerate_key_fn,
        )

        data = RegenerateKeyRequest(key="sk-test", allowed_routes=["/*"])
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

        with patch("litellm.proxy.proxy_server.premium_user", False):
            with pytest.raises(ProxyException) as exc_info:
                await regenerate_key_fn(
                    key=None,
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)
        assert "Enterprise" not in str(exc_info.value.message)

    @pytest.mark.asyncio
    async def test_non_admin_generate_key_explicit_empty_allowed_routes_rejected(self):
        """`generate_key_fn` rejects a non-admin when `allowed_routes` is
        present as `[]` in the request body. The value matches the model
        default but `model_fields_set` distinguishes the two, so the
        explicit-empty case on the create path is caught."""
        data = GenerateKeyRequest(key_alias="plain-key", allowed_routes=[])
        assert "allowed_routes" in data.model_fields_set
        user_api_key_dict = UserAPIKeyAuth(
            user_id="internal-user-123",
            user_role=LitellmUserRoles.INTERNAL_USER,
        )
        mock_prisma_client = AsyncMock()

        with (
            patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
            patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
            patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
                new_callable=AsyncMock,
                return_value=MagicMock(),
            ),
        ):
            with pytest.raises(ProxyException) as exc_info:
                await generate_key_fn(
                    data=data,
                    user_api_key_dict=user_api_key_dict,
                    litellm_changed_by=None,
                )
        assert str(exc_info.value.code) == "403"
        assert "allowed_routes" in str(exc_info.value.message)

    def test_helper_accepts_derived_safe_preset_for_non_admin(self):
        """`_check_allowed_routes_caller_permission` accepts a non-admin
        when `allow_safe_presets=True` and `allowed_routes` is entirely
        composed of `_NON_ADMIN_SAFE_ALLOWED_ROUTES_PRESETS` tokens. This
        is the shape the post-`handle_key_type` recheck at line 914 uses
        after deriving `["llm_api_routes"]` from `key_type=llm_api`."""
        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _check_allowed_routes_caller_permission,
        )

        _check_allowed_routes_caller_permission(
            allowed_routes=["llm_api_routes"],
            user_api_key_dict=UserAPIKeyAuth(
                user_id="internal-user-123",
                user_role=LitellmUserRoles.INTERNAL_USER,
            ),
            allow_safe_presets=True,
        )
        _check_allowed_routes_caller_permission(
            allowed_routes=["info_routes"],
            user_api_key_dict=UserAPIKeyAuth(
                user_id="internal-user-123",
                user_role=LitellmUserRoles.INTERNAL_USER,
            ),
            allow_safe_presets=True,
        )

    def test_helper_rejects_derived_unsafe_preset_for_non_admin(self):
        """`_check_allowed_routes_caller_permission` rejects a non-admin
        when `allow_safe_presets=True` but the derived value is outside
        `_NON_ADMIN_SAFE_ALLOWED_ROUTES_PRESETS` (for example
        `["management_routes"]` from `key_type=management`)."""
        from fastapi import HTTPException

        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _check_allowed_routes_caller_permission,
        )

        with pytest.raises(HTTPException) as exc_info:
            _check_allowed_routes_caller_permission(
                allowed_routes=["management_routes"],
                user_api_key_dict=UserAPIKeyAuth(
                    user_id="internal-user-123",
                    user_role=LitellmUserRoles.INTERNAL_USER,
                ),
                allow_safe_presets=True,
            )
        assert exc_info.value.status_code == 403
        assert "allowed_routes" in str(exc_info.value.detail)

    def test_helper_rejects_when_provided_and_none_without_typeerror(self):
        """`_check_allowed_routes_caller_permission` returns a 403 (not a
        TypeError from iterating `None`) when a caller ever combines
        `allowed_routes_was_provided=True` with `allowed_routes=None` and
        `allow_safe_presets=True`. Pins the `and allowed_routes` guard on
        the safe-preset branch."""
        from fastapi import HTTPException

        from litellm.proxy.management_endpoints.key_management_endpoints import (
            _check_allowed_routes_caller_permission,
        )

        with pytest.raises(HTTPException) as exc_info:
            _check_allowed_routes_caller_permission(
                allowed_routes=None,
                user_api_key_dict=UserAPIKeyAuth(
                    user_id="internal-user-123",
                    user_role=LitellmUserRoles.INTERNAL_USER,
                ),
                allowed_routes_was_provided=True,
                allow_safe_presets=True,
            )
        assert exc_info.value.status_code == 403
        assert "allowed_routes" in str(exc_info.value.detail)


def test_jinja_prompt_manager_is_sandboxed():
    """
    PromptManager renders user-supplied templates via /prompts/test, so its
    jinja env must reject access to unsafe Python attributes like
    ``__class__`` and ``__mro__``.
    """
    from jinja2.exceptions import SecurityError

    from litellm.integrations.dotprompt.prompt_manager import PromptManager

    pm = PromptManager()
    template = pm.jinja_env.from_string("{{ ''.__class__.__mro__ }}")
    with pytest.raises(SecurityError):
        template.render()


def test_validate_public_image_url_rejects_local_paths():
    from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
        _validate_public_image_url,
    )

    for bad in ("/etc/passwd", "file:///etc/passwd", "../../etc/passwd"):
        with pytest.raises(HTTPException) as exc_info:
            _validate_public_image_url(bad, "logo_url")
        assert exc_info.value.status_code == 400


def test_validate_public_image_url_accepts_http_and_noop_empty():
    from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (
        _validate_public_image_url,
    )

    _validate_public_image_url("https://example.com/logo.png", "logo_url")
    _validate_public_image_url("http://cdn.internal/logo.svg", "logo_url")
    _validate_public_image_url(None, "logo_url")
    _validate_public_image_url("", "logo_url")
    _validate_public_image_url("   ", "logo_url")


@pytest.mark.asyncio
async def test_process_single_key_update_cache_invalidation_with_token_hash():
    """
    _process_single_key_update must pass the token hash as-is (not
    double-hashed) to _delete_cache_key_object when the key is already a
    pre-hashed token ID rather than an sk- prefixed key.

    Without this, cache invalidation silently fails: the wrong cache entry
    is deleted while the stale entry (with outdated fields) persists and
    gets refreshed indefinitely by update_cache on every successful request.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _process_single_key_update,
    )

    token_hash = "abc123def456"

    existing_key = LiteLLM_VerificationToken(
        token=token_hash,
        user_id="user-1",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
        tags=None,
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=existing_key
    )
    mock_updated = MagicMock()
    mock_updated.model_dump.return_value = {"max_budget": 100.0}
    mock_prisma_client.update_data = AsyncMock(return_value={"data": mock_updated})

    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()
    mock_llm_router = MagicMock()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.prepare_key_update_data",
            return_value={"max_budget": 100.0},
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
            return_value=None,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ) as mock_delete_cache,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook",
            new_callable=AsyncMock,
        ),
    ):
        update_key_request = UpdateKeyRequest(
            key=token_hash,
            max_budget=100.0,
        )

        user_api_key_dict = UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin-user",
        )

        await _process_single_key_update(
            update_key_request=update_key_request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            prisma_client=mock_prisma_client,
            user_api_key_cache=mock_user_api_key_cache,
            proxy_logging_obj=mock_proxy_logging_obj,
            llm_router=mock_llm_router,
        )

        mock_delete_cache.assert_called_once()
        call_kwargs = mock_delete_cache.call_args.kwargs
        # The token hash should be passed as-is, NOT double-hashed
        assert call_kwargs["hashed_token"] == token_hash


@pytest.mark.asyncio
async def test_process_single_key_update_non_admin_permissions_rejected():
    """`_process_single_key_update` rejects a non-admin when `permissions`
    is present in the constructed `UpdateKeyRequest`. Guards the bulk path
    against a future widening of the `BulkUpdateKeyRequestItem` or
    `KeyUpdateFields` allowlists reopening the class."""
    update_key_request = UpdateKeyRequest(
        key="abc123",
        permissions={"get_spend_routes": True},
    )
    assert "permissions" in update_key_request.model_fields_set

    non_admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-non-admin",
        user_id="user-1",
    )

    with pytest.raises(HTTPException) as exc_info:
        await _process_single_key_update(
            update_key_request=update_key_request,
            user_api_key_dict=non_admin,
            litellm_changed_by=None,
            prisma_client=AsyncMock(),
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=MagicMock(),
        )
    assert exc_info.value.status_code == 403
    assert "permissions" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_process_single_key_update_non_admin_permissions_explicit_empty_rejected():
    """`_process_single_key_update` rejects a non-admin when `permissions`
    is present as `{}` in the constructed `UpdateKeyRequest`. Presence
    check on `model_fields_set` catches the explicit-empty case the same
    as any other value."""
    update_key_request = UpdateKeyRequest(key="abc123", permissions={})
    assert "permissions" in update_key_request.model_fields_set

    non_admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-non-admin",
        user_id="user-1",
    )

    with pytest.raises(HTTPException) as exc_info:
        await _process_single_key_update(
            update_key_request=update_key_request,
            user_api_key_dict=non_admin,
            litellm_changed_by=None,
            prisma_client=AsyncMock(),
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=MagicMock(),
        )
    assert exc_info.value.status_code == 403
    assert "permissions" in str(exc_info.value.detail)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "fields",
    [{"metadata": {}}, {"metadata": None}, {"denied_passthrough_routes": []}],
    ids=["metadata_replaced", "metadata_null", "denies_cleared"],
)
async def test_process_single_key_update_non_admin_cannot_drop_stored_denied_passthrough_routes(
    fields: dict[str, object],
) -> None:
    stored_key: Final = LiteLLM_VerificationToken(
        token="hashed-key", user_id="key-owner", metadata={"denied_passthrough_routes": ["/svc/admin"]}
    )
    prisma_client: Final = AsyncMock()

    with pytest.raises(HTTPException) as exc_info:
        await _process_single_key_update(
            update_key_request=UpdateKeyRequest.model_validate({"key": "sk-owned-key", **fields}),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="team-admin"),
            litellm_changed_by=None,
            prisma_client=prisma_client,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=MagicMock(),
            existing_key_row=stored_key,
        )

    assert exc_info.value.status_code == 403
    assert "denied_passthrough_routes" in str(exc_info.value.detail)
    prisma_client.update_data.assert_not_called()


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_cache_invalidation_with_token_hash():
    """
    _execute_virtual_key_regeneration must pass the token hash as-is (not
    double-hashed) to _delete_cache_key_object when the key is a
    pre-hashed token ID.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    token_hash = "abc123def456"

    existing_key = LiteLLM_VerificationToken(
        token=token_hash,
        user_id="user-1",
        models=["gpt-4"],
        team_id=None,
        max_budget=None,
        tags=None,
    )

    mock_prisma_client = AsyncMock()

    # _execute_virtual_key_regeneration calls dict(updated_token) which
    # needs the return value to be iterable as key-value pairs.
    class DictLikeResult:
        def __init__(self, data):
            self._data = data

        def __iter__(self):
            return iter(self._data.items())

    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=DictLikeResult(
            {"token": "new-hashed-token", "key_name": "sk-...ab12", "user_id": "user-1"}
        )
    )
    mock_prisma_client.db.litellm_verificationtoken.create = AsyncMock(
        return_value=None
    )
    mock_prisma_client.jsonify_object = MagicMock(side_effect=lambda data: data)

    mock_user_api_key_cache = MagicMock()
    mock_proxy_logging_obj = MagicMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin-user",
    )

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ) as mock_delete_cache,
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.prepare_key_update_data",
            new_callable=AsyncMock,
            return_value={},
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key=token_hash,
            key=token_hash,
            data=None,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            user_api_key_cache=mock_user_api_key_cache,
            proxy_logging_obj=mock_proxy_logging_obj,
        )

        mock_delete_cache.assert_called_once()
        call_kwargs = mock_delete_cache.call_args.kwargs
        # The token hash should be passed as-is, NOT double-hashed
        assert call_kwargs["hashed_token"] == token_hash


# ---------------------------------------------------------------------------
# /team/key/bulk_update tests
# ---------------------------------------------------------------------------


_BULK_PKG = "litellm.proxy.management_endpoints.key_management_endpoints"


def _make_team_key(token: str, team_id: str = "team-abc") -> LiteLLM_VerificationToken:
    return LiteLLM_VerificationToken(
        token=token,
        user_id="user-123",
        models=[],
        team_id=team_id,
        max_budget=None,
    )


def _admin() -> UserAPIKeyAuth:
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin", user_id="admin"
    )


def _internal_user() -> UserAPIKeyAuth:
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-iu", user_id="iu"
    )


def _updated(payload):
    m = MagicMock()
    m.model_dump.return_value = payload
    return m


def _setup_team_keys_mocks(
    monkeypatch,
    *,
    find_many=None,
    find_unique=None,
    update_data=None,
    hash_identity=True,
):
    """Set up mocks for bulk_update_team_keys; returns mock_prisma."""
    mock_prisma = AsyncMock()
    mock_prisma.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[] if find_many is None else find_many
    )
    if find_unique is not None:
        mock_prisma.db.litellm_verificationtoken.find_unique = find_unique
    if update_data is not None:
        mock_prisma.update_data = update_data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.user_custom_key_update", None)
    monkeypatch.setattr(
        f"{_BULK_PKG}.prepare_key_update_data",
        AsyncMock(return_value={"max_budget": 50.0}),
    )
    monkeypatch.setattr(f"{_BULK_PKG}.delete_cache_key_object", AsyncMock())
    monkeypatch.setattr(
        f"{_BULK_PKG}.KeyManagementEventHooks.async_key_updated_hook", AsyncMock()
    )
    monkeypatch.setattr(f"{_BULK_PKG}.get_team_object", AsyncMock(return_value=None))
    monkeypatch.setattr(f"{_BULK_PKG}._check_team_key_limits", AsyncMock())
    monkeypatch.setattr(
        f"{_BULK_PKG}.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
        AsyncMock(),
    )
    if hash_identity:
        # Tests use already-hashed tokens; the raw-sk regression opts out.
        monkeypatch.setattr(f"{_BULK_PKG}.hash_token_if_needed", lambda token: token)
    return mock_prisma


async def _call_as_admin(data):
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_team_keys,
    )

    return await bulk_update_team_keys(
        data=data, user_api_key_dict=_admin(), litellm_changed_by=None
    )


# ---- happy paths ----------------------------------------------------------


@pytest.mark.asyncio
async def test_bulk_update_team_keys_success_with_key_ids(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    keys = [_make_team_key("tok-a"), _make_team_key("tok-b")]
    find_unique = AsyncMock(side_effect=keys)
    mock = _setup_team_keys_mocks(
        monkeypatch,
        find_many=keys,
        find_unique=find_unique,
        update_data=AsyncMock(
            side_effect=[{"data": _updated({"max_budget": 50.0})}] * 2
        ),
    )

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            key_ids=["tok-a", "tok-b"],
            update_fields=KeyUpdateFields(max_budget=50.0),
        )
    )

    assert len(response.successful_updates) == 2
    assert len(response.failed_updates) == 0
    where = mock.db.litellm_verificationtoken.find_many.await_args.kwargs["where"]
    assert where["team_id"] == "team-abc"
    assert where["token"] == {"in": ["tok-a", "tok-b"]}
    find_unique.assert_not_called()


@pytest.mark.asyncio
async def test_bulk_update_team_keys_success_all_keys_in_team(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    keys = [_make_team_key(f"tok-{i}") for i in range(3)]
    find_unique = AsyncMock(side_effect=keys)
    mock = _setup_team_keys_mocks(
        monkeypatch,
        find_many=keys,
        find_unique=find_unique,
        update_data=AsyncMock(
            side_effect=[{"data": _updated({"max_budget": 50.0})}] * 3
        ),
    )

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            all_keys_in_team=True,
            update_fields=KeyUpdateFields(max_budget=50.0),
        )
    )

    assert len(response.successful_updates) == 3
    where = mock.db.litellm_verificationtoken.find_many.await_args.kwargs["where"]
    # `blocked` is Boolean? with no default → /key/generate writes NULL. Prisma's
    # NOT excludes NULLs, so the filter has to OR `false` with `null` explicitly.
    blocked_or, expires_or = where["AND"][0]["OR"], where["AND"][1]["OR"]
    assert {"blocked": False} in blocked_or and {"blocked": None} in blocked_or
    assert {"expires": None} in expires_or
    assert any(
        "gt" in c.get("expires", {})
        for c in expires_or
        if isinstance(c.get("expires"), dict)
    )
    find_unique.assert_not_called()


@pytest.mark.asyncio
async def test_bulk_update_team_keys_key_not_in_team(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    in_team = _make_team_key("tok-a")
    _setup_team_keys_mocks(
        monkeypatch,
        find_many=[in_team],
        find_unique=AsyncMock(return_value=in_team),
        update_data=AsyncMock(return_value={"data": _updated({"max_budget": 50.0})}),
    )

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            key_ids=["tok-a", "tok-foreign"],
            update_fields=KeyUpdateFields(max_budget=50.0),
        )
    )
    assert [u.key for u in response.successful_updates] == ["tok-a"]
    assert [u.key for u in response.failed_updates] == ["tok-foreign"]
    assert "not found in team" in response.failed_updates[0].failed_reason


# ---- error paths ----------------------------------------------------------


@pytest.mark.asyncio
async def test_bulk_update_team_keys_batch_size_cap(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    _setup_team_keys_mocks(
        monkeypatch,
        find_many=[_make_team_key(f"tok-{i}") for i in range(501)],
    )

    with pytest.raises(HTTPException) as exc:
        await _call_as_admin(
            BulkUpdateTeamKeysRequest(
                team_id="team-abc",
                all_keys_in_team=True,
                update_fields=KeyUpdateFields(max_budget=50.0),
            )
        )
    assert exc.value.status_code == 400
    assert "more than 500" in exc.value.detail["error"]


@pytest.mark.asyncio
async def test_bulk_update_team_keys_empty_team_returns_404(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    _setup_team_keys_mocks(monkeypatch, find_many=[])
    with pytest.raises(HTTPException) as exc:
        await _call_as_admin(
            BulkUpdateTeamKeysRequest(
                team_id="team-empty",
                all_keys_in_team=True,
                update_fields=KeyUpdateFields(max_budget=50.0),
            )
        )
    assert exc.value.status_code == 404


# ---- auth -----------------------------------------------------------------


@pytest.mark.asyncio
async def test_bulk_update_team_keys_team_member_with_permission(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_team_keys,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    key_a = _make_team_key("tok-a")
    _setup_team_keys_mocks(
        monkeypatch,
        find_many=[key_a],
        find_unique=AsyncMock(return_value=key_a),
        update_data=AsyncMock(return_value={"data": _updated({"max_budget": 50.0})}),
    )
    auth_check = AsyncMock()
    monkeypatch.setattr(
        f"{_BULK_PKG}.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
        auth_check,
    )

    response = await bulk_update_team_keys(
        data=BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            all_keys_in_team=True,
            update_fields=KeyUpdateFields(max_budget=50.0),
        ),
        user_api_key_dict=_internal_user(),
        litellm_changed_by=None,
    )
    assert len(response.successful_updates) == 1
    # Upfront check + per-key check inside _process_single_key_update
    assert auth_check.await_count == 2


@pytest.mark.asyncio
async def test_bulk_update_team_keys_team_member_no_permission(monkeypatch):
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_team_keys,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    mock = _setup_team_keys_mocks(monkeypatch, find_many=[_make_team_key("tok-a")])
    monkeypatch.setattr(
        f"{_BULK_PKG}.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
        AsyncMock(
            side_effect=ProxyException(
                message="not in team",
                type="team_member_permission_error",
                param="/key/update",
                code=401,
            )
        ),
    )

    with pytest.raises(ProxyException):
        await bulk_update_team_keys(
            data=BulkUpdateTeamKeysRequest(
                team_id="team-abc",
                all_keys_in_team=True,
                update_fields=KeyUpdateFields(max_budget=1.0),
            ),
            user_api_key_dict=_internal_user(),
            litellm_changed_by=None,
        )
    mock.update_data.assert_not_called()


def test_handle_key_type_persists_key_type_and_derives_routes():
    """`handle_key_type` keeps `key_type` in the payload (so it is persisted on
    the token) while still deriving the `allowed_routes` preset. Regression for
    the UI showing scoped keys as "All Proxy Models": the frontend now reads the
    persisted `key_type` instead of reverse-mapping the preset string."""
    from litellm.proxy._types import GenerateKeyRequest, LiteLLMKeyType
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        handle_key_type,
    )

    cases = {
        LiteLLMKeyType.MANAGEMENT: ("management", ["management_routes"]),
        LiteLLMKeyType.READ_ONLY: ("read_only", ["info_routes"]),
        LiteLLMKeyType.LLM_API: ("llm_api", ["llm_api_routes"]),
    }
    for key_type, (expected_type, expected_routes) in cases.items():
        data = GenerateKeyRequest(key_type=key_type)
        out = handle_key_type(data, {"key_type": key_type})
        assert out["key_type"] == expected_type
        assert out["allowed_routes"] == expected_routes


def test_handle_key_type_default_persists_type_without_forcing_routes():
    """`default` is persisted but must not overwrite an explicit `allowed_routes`
    (e.g. a SCIM key created with `["/scim/*"]` and no explicit key_type)."""
    from litellm.proxy._types import GenerateKeyRequest, LiteLLMKeyType
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        handle_key_type,
    )

    data = GenerateKeyRequest(key_type=LiteLLMKeyType.DEFAULT)
    out = handle_key_type(data, {"allowed_routes": ["/scim/*"], "key_type": LiteLLMKeyType.DEFAULT})
    assert out["key_type"] == "default"
    assert out["allowed_routes"] == ["/scim/*"]


def test_handle_key_type_none_drops_key_type():
    """When no `key_type` is supplied the payload must not carry a `key_type`
    entry, so old keys stay `null` and the frontend keeps its route fallback."""
    from litellm.proxy._types import GenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        handle_key_type,
    )

    data = GenerateKeyRequest(key_type=None)
    out = handle_key_type(data, {"key_type": None})
    assert "key_type" not in out


# ---- pydantic-layer validation -------------------------------------------


def test_bulk_update_team_keys_request_validation():
    """Allowlist (extra='forbid'), empty-payload rejection, and selection XOR."""
    from pydantic import ValidationError

    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    forbidden = [
        "key",
        "key_alias",
        "team_id",
        "allowed_routes",
        "allowed_passthrough_routes",
        "permissions",
        "object_permission",
        "access_group_ids",
        "user_id",
        "organization_id",
        "blocked",
        "key_type",
        "models",
        "config",
        "router_settings",
        "spend",
    ]
    for f in forbidden:
        with pytest.raises(ValidationError, match=f):
            KeyUpdateFields(**{f: True})

    with pytest.raises(ValidationError, match="at least one"):
        KeyUpdateFields()

    assert KeyUpdateFields(max_budget=50.0, tags=["x"]).max_budget == 50.0

    valid = KeyUpdateFields(max_budget=10)
    with pytest.raises(ValidationError):
        BulkUpdateTeamKeysRequest(
            team_id="t", key_ids=["k"], all_keys_in_team=True, update_fields=valid
        )
    with pytest.raises(ValidationError):
        BulkUpdateTeamKeysRequest(team_id="t", update_fields=valid)


# ---- security regressions ------------------------------------------------


@pytest.mark.asyncio
async def test_bulk_update_team_keys_hashes_raw_sk_key_ids(monkeypatch):
    """Regression: raw sk-... key_ids must be hashed before the find_many lookup."""
    from litellm.proxy._types import hash_token
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    raw_sk = "sk-rawkey1234567890"
    hashed = hash_token(raw_sk)
    row = LiteLLM_VerificationToken(
        token=hashed, user_id="u", models=[], team_id="team-abc", max_budget=None
    )
    mock = _setup_team_keys_mocks(
        monkeypatch,
        find_many=[row],
        find_unique=AsyncMock(return_value=row),
        update_data=AsyncMock(return_value={"data": _updated({"max_budget": 50.0})}),
        hash_identity=False,
    )

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            key_ids=[raw_sk],
            update_fields=KeyUpdateFields(max_budget=50.0),
        )
    )
    where = mock.db.litellm_verificationtoken.find_many.await_args.kwargs["where"]
    assert where["token"] == {"in": [hashed]}
    # Response reports the user-supplied form, not the hash.
    assert response.successful_updates[0].key == raw_sk


@pytest.mark.asyncio
async def test_bulk_update_team_keys_auth_check_runs_when_no_keys_match(monkeypatch):
    """Regression: non-admin with bogus key_ids must still hit the membership gate."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_team_keys,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    mock = _setup_team_keys_mocks(monkeypatch, find_many=[])
    auth_check = AsyncMock(
        side_effect=ProxyException(
            message="not in team",
            type="team_member_permission_error",
            param="/key/update",
            code=401,
        )
    )
    monkeypatch.setattr(
        f"{_BULK_PKG}.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
        auth_check,
    )

    with pytest.raises(ProxyException):
        await bulk_update_team_keys(
            data=BulkUpdateTeamKeysRequest(
                team_id="victim-team",
                key_ids=["bogus-1", "bogus-2"],
                update_fields=KeyUpdateFields(max_budget=1.0),
            ),
            user_api_key_dict=_internal_user(),
            litellm_changed_by=None,
        )
    # Anchored on data.team_id, not existing_keys[0].
    assert auth_check.await_args.kwargs["existing_key_row"].team_id == "victim-team"
    mock.update_data.assert_not_called()


@pytest.mark.asyncio
async def test_bulk_update_team_keys_does_not_log_raw_sk_token_on_failure(
    monkeypatch, caplog
):
    """Regression: per-key failure must not log the raw sk-... (ERROR-level logs persist)."""
    import logging

    from litellm.proxy._types import hash_token
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    raw_sk = "sk-supersecret1234567890"
    row = LiteLLM_VerificationToken(
        token=hash_token(raw_sk),
        user_id="u",
        models=[],
        team_id="team-abc",
        max_budget=None,
    )
    _setup_team_keys_mocks(
        monkeypatch,
        find_many=[row],
        update_data=AsyncMock(side_effect=RuntimeError("boom")),
        hash_identity=False,
    )

    with caplog.at_level(logging.ERROR, logger="LiteLLM Proxy"):
        response = await _call_as_admin(
            BulkUpdateTeamKeysRequest(
                team_id="team-abc",
                key_ids=[raw_sk],
                update_fields=KeyUpdateFields(max_budget=50.0),
            )
        )
    assert len(response.failed_updates) == 1
    log_text = "\n".join(r.getMessage() for r in caplog.records)
    assert raw_sk not in log_text


@pytest.mark.asyncio
async def test_bulk_update_team_keys_propagates_team_id_to_per_key_request(monkeypatch):
    """Regression: per-key UpdateKeyRequest carries data.team_id (gates _check_team_key_limits)."""
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    _setup_team_keys_mocks(monkeypatch, find_many=[_make_team_key("tok-a")])
    captured = []

    async def fake_process(*, update_key_request, **kw):
        captured.append(update_key_request)
        return {"max_budget": update_key_request.max_budget}

    monkeypatch.setattr(f"{_BULK_PKG}._process_single_key_update", fake_process)

    await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            key_ids=["tok-a"],
            update_fields=KeyUpdateFields(
                tpm_limit=10_000, tpm_limit_type="guaranteed_throughput"
            ),
        )
    )
    assert captured[0].team_id == "team-abc"
    assert captured[0].tpm_limit_type == "guaranteed_throughput"


@pytest.mark.asyncio
async def test_bulk_update_team_keys_dedupes_key_ids(monkeypatch):
    """Duplicate key_ids collapse to a single update (no redundant DB writes, no inflated counts)."""
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    key_a = _make_team_key("tok-a")
    update_data = AsyncMock(return_value={"data": _updated({"max_budget": 50.0})})
    _setup_team_keys_mocks(
        monkeypatch,
        find_many=[key_a],
        find_unique=AsyncMock(return_value=key_a),
        update_data=update_data,
    )

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc",
            key_ids=["tok-a", "tok-a", "tok-a"],
            update_fields=KeyUpdateFields(max_budget=50.0),
        )
    )

    assert response.total_requested == 1
    assert len(response.successful_updates) == 1
    assert len(response.failed_updates) == 0
    update_data.assert_awaited_once()


@pytest.mark.asyncio
async def test_bulk_update_team_keys_blocks_metadata_allowed_passthrough_routes(
    monkeypatch,
):
    """Non-admin can't grant passthrough access by smuggling allowed_passthrough_routes through metadata."""
    from fastapi import HTTPException

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        bulk_update_team_keys,
    )
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    mock = _setup_team_keys_mocks(monkeypatch, find_many=[_make_team_key("tok-a")])

    request = BulkUpdateTeamKeysRequest(
        team_id="team-abc",
        all_keys_in_team=True,
        update_fields=KeyUpdateFields(
            metadata={"allowed_passthrough_routes": ["/admin/*"]}
        ),
    )

    with pytest.raises(HTTPException) as exc:
        await bulk_update_team_keys(
            data=request,
            user_api_key_dict=_internal_user(),
            litellm_changed_by=None,
        )

    assert exc.value.status_code == 403
    assert "allowed_passthrough_routes" in str(exc.value.detail)
    mock.update_data.assert_not_called()


# ---------------------------------------------------------------------------
# /key/regenerate ownership-rebind guard + premium-gate identity check
# ---------------------------------------------------------------------------

import contextlib  # noqa: E402


def _non_admin_user_api_key_dict():
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
    )


@contextlib.contextmanager
def _patch_regenerate_side_effects():
    """Mock out token creation + DB write + cache + rotation hook so
    ``_execute_virtual_key_regeneration`` runs to completion under test."""
    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
    ):
        yield


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "incoming_user_id,expected_status,expected_substring",
    [
        # Cross-user rebind: the privesc primitive.
        ("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",
        "explicit_null_blocked",
        "same_user_id_allowed",
    ],
)
async def test_regenerate_user_id_rebind_guard(
    incoming_user_id, expected_status, expected_substring
):
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    existing_key = _make_regenerate_existing_key()
    data = RegenerateKeyRequest(user_id=incoming_user_id)

    async def _run():
        await _execute_virtual_key_regeneration(
            prisma_client=_make_regenerate_mock_prisma(),
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=data,
            user_api_key_dict=_non_admin_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    if expected_status is None:
        with _patch_regenerate_side_effects():
            await _run()
        return

    with pytest.raises(HTTPException) as exc:
        await _run()
    assert exc.value.status_code == expected_status
    assert expected_substring in str(exc.value.detail)


@pytest.mark.asyncio
async def test_regenerate_premium_gate_requires_actual_master_key():
    # ``regenerate_key_fn``'s decorator wraps the underlying ValueError
    # into a ProxyException with empty ``message``. The exception type
    # alone confirms the premium gate fired.
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    data = RegenerateKeyRequest(key="sk-not-master", new_master_key="anything")

    with (
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.master_key", "sk-the-real-master-key"),
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        pytest.raises((ValueError, HTTPException, ProxyException)),
    ):
        await regenerate_key_fn(
            key="sk-not-master",
            data=data,
            user_api_key_dict=_non_admin_user_api_key_dict(),
        )


@pytest.mark.asyncio
async def test_regenerate_premium_gate_allows_actual_master_key_holder():
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    master = "sk-the-real-master-key"
    data = RegenerateKeyRequest(key=master, new_master_key="sk-new-master")

    with (
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.master_key", master),
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.rotate_master_key",
            new_callable=AsyncMock,
        ),
    ):
        result = await regenerate_key_fn(
            key=master,
            data=data,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key=master,
                user_id="admin",
            ),
        )

    assert result.token == "sk-new-master"


@pytest.mark.asyncio
async def test_regenerate_applies_normalized_mcp_object_permission():
    from litellm.proxy._types import (
        LiteLLM_ObjectPermissionBase,
        RegenerateKeyRequest,
    )
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    data = RegenerateKeyRequest(
        key="sk-old",
        object_permission=LiteLLM_ObjectPermissionBase(mcp_servers=["server-alias"]),
    )
    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = AsyncMock()
    mock_repo = MagicMock()
    mock_repo.table.find_unique = AsyncMock(return_value=existing_key)
    execute_mock = AsyncMock(return_value=MagicMock())

    with (
        patch("litellm.proxy.proxy_server.premium_user", True),
        patch("litellm.proxy.proxy_server.master_key", None),
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.hash_token", lambda token: "hashed-old"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.VerificationTokenRepository",
            return_value=mock_repo,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.enforce_member_can_assign_access_groups",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.can_modify_verification_token",
            new_callable=AsyncMock,
            return_value=True,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_mcp_servers_against_team",
            new_callable=AsyncMock,
            return_value={"mcp_servers": ["server-id"]},
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_search_tools_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_vector_stores_against_team",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._execute_virtual_key_regeneration",
            execute_mock,
        ),
    ):
        await regenerate_key_fn(
            key="sk-old",
            data=data,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN.value,
                api_key="sk-admin",
                user_id="admin",
            ),
        )

    regenerated_data = execute_mock.await_args.kwargs["data"]
    assert regenerated_data.object_permission.mcp_servers == ["server-id"]


# ---------------------------------------------------------------------------
# Regression tests for GHSA-q775-qw9r-2r4g: budget escalation via key/generate
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_ghsa_q775_non_admin_unlimited_can_delegate_budget():
    """
    Non-admin caller with max_budget=None (unlimited) can legitimately create
    budget-capped keys. Any finite budget is within an unlimited ceiling.
    """
    data = GenerateKeyRequest(max_budget=999999)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
        max_budget=None,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
            new_callable=AsyncMock,
            return_value=MagicMock(),
        ),
    ):
        result = await generate_key_fn(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        assert result is not None


@pytest.mark.asyncio
async def test_ghsa_q775_non_admin_cannot_exceed_own_budget():
    """
    Non-admin caller with max_budget=100 must not be able to create a key
    with max_budget=500.
    """
    data = GenerateKeyRequest(max_budget=500)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
        max_budget=100,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
    ):
        with pytest.raises((HTTPException, ProxyException)) as exc_info:
            await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )
        err = exc_info.value
        code = getattr(err, "status_code", None) or getattr(err, "code", None)
        msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
        assert str(code) == "400"
        assert "cannot exceed" in msg.lower()


@pytest.mark.asyncio
async def test_ghsa_q775_non_admin_within_budget_allowed():
    """
    Non-admin caller with max_budget=100 can create a key with max_budget=50.
    """
    data = GenerateKeyRequest(max_budget=50)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
        max_budget=100,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
            new_callable=AsyncMock,
            return_value=MagicMock(),
        ),
    ):
        result = await generate_key_fn(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        assert result is not None


@pytest.mark.asyncio
async def test_ghsa_q775_upperbound_default_not_rejected():
    """
    When upperbound_key_generate_params fills max_budget as a default, the
    ceiling check must NOT fire — only explicitly requested budgets trigger it.
    """
    data = GenerateKeyRequest()
    assert data.max_budget is None

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
        max_budget=None,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
        patch(
            "litellm.upperbound_key_generate_params",
            MagicMock(max_budget=100.0),
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
            new_callable=AsyncMock,
            return_value=MagicMock(),
        ),
    ):
        result = await generate_key_fn(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        assert result is not None


@pytest.mark.asyncio
async def test_ghsa_q775_default_key_generate_params_not_rejected():
    """
    When default_key_generate_params fills max_budget, the ceiling check must
    NOT fire — only caller-supplied budgets trigger it.
    """
    data = GenerateKeyRequest()
    assert data.max_budget is None

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-internal",
        user_id="user-1",
        max_budget=None,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
        patch(
            "litellm.default_key_generate_params",
            {"max_budget": 50.0},
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
            new_callable=AsyncMock,
            return_value=MagicMock(),
        ),
    ):
        result = await generate_key_fn(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        assert result is not None


@pytest.mark.asyncio
async def test_ghsa_q775_admin_bypasses_budget_ceiling():
    """
    Admin caller can set any max_budget regardless of own budget.
    """
    data = GenerateKeyRequest(max_budget=999999)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin-1",
        max_budget=None,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._common_key_generation_helper",
            new_callable=AsyncMock,
            return_value=MagicMock(),
        ),
    ):
        result = await generate_key_fn(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )
        assert result is not None


@pytest.mark.asyncio
async def test_ghsa_q775_ui_session_token_team_key_exempt_from_budget_ceiling():
    """
    Regression: a UI/CLI session token (team_id=litellm-dashboard) creating a
    TEAM key (data.team_id set) is exempt from the delegated-authority ceiling.
    The session max_budget is a per-session chat spend cap (max_ui_session_budget,
    default $0.25), not a delegation authority, and the team key's spend is bounded
    by the team budget at request time. This is the team-admin key-creation flow
    blocked since v1.86.x. Calls the helper directly so the ceiling runs (mocking
    out _common_key_generation_helper would mock out the check under test).
    """
    from litellm.constants import UI_SESSION_TOKEN_TEAM_ID

    data = GenerateKeyRequest(max_budget=500, team_id="team-abc")
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-ui-session",
        user_id="user-1",
        team_id=UI_SESSION_TOKEN_TEAM_ID,
        max_budget=0.25,
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "default_user_id"),
    ):
        try:
            await _common_key_generation_helper(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                team_table=MagicMock(),
            )
        except (HTTPException, ProxyException) as err:
            msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
            assert (
                "cannot exceed" not in msg.lower()
            ), "UI/CLI session token creating a team key must be exempt from the ceiling"


@pytest.mark.asyncio
async def test_ghsa_q775_ui_session_token_personal_key_still_capped():
    """
    Security regression for GHSA-q775: the session-token exemption must NOT extend
    to personal keys. A UI/CLI session token (team_id=litellm-dashboard) creating a
    key with no data.team_id is still bound by the ceiling; otherwise a session
    token - or a leaked one, whose blast radius is the $0.25 chat cap - could mint
    an arbitrary-budget personal key, the exact escalation GHSA-q775 closed. Unlike
    a team key, nothing else bounds a personal key's spend.
    """
    from litellm.constants import UI_SESSION_TOKEN_TEAM_ID

    data = GenerateKeyRequest(max_budget=500)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-ui-session",
        user_id="user-1",
        team_id=UI_SESSION_TOKEN_TEAM_ID,
        max_budget=0.25,
    )

    mock_prisma_client = AsyncMock()

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.user_custom_key_generate", None),
    ):
        with pytest.raises((HTTPException, ProxyException)) as exc_info:
            await generate_key_fn(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
            )
        err = exc_info.value
        code = getattr(err, "status_code", None) or getattr(err, "code", None)
        msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
        assert str(code) == "400"
        assert "cannot exceed" in msg.lower()


@pytest.mark.asyncio
async def test_ui_session_token_personal_key_ceiling_is_user_budget():
    from litellm.constants import UI_SESSION_TOKEN_TEAM_ID

    data = GenerateKeyRequest(max_budget=100)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-ui-session",
        user_id="user-1",
        team_id=UI_SESSION_TOKEN_TEAM_ID,
        max_budget=1.0,
        user_max_budget=500.0,
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),  # test-quality-ok: helper reads proxy_server.prisma_client directly
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),  # test-quality-ok: helper reads proxy_server.user_api_key_cache directly
        patch("litellm.proxy.proxy_server.llm_router", None),  # test-quality-ok: helper reads proxy_server.llm_router directly
        patch("litellm.proxy.proxy_server.premium_user", False),  # test-quality-ok: helper reads proxy_server.premium_user directly
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "default_user_id"),  # test-quality-ok: helper reads proxy_server.litellm_proxy_admin_name directly
        patch(  # test-quality-ok: helper has no dependency injection seam for key persistence
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):
        mock_generate_key.return_value = {"key": "sk-test-key", "token_id": "token-id"}
        try:
            await _common_key_generation_helper(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                team_table=None,
            )
        except (HTTPException, ProxyException) as err:
            msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
            assert "cannot exceed" not in msg.lower()


@pytest.mark.asyncio
async def test_ui_session_token_personal_key_above_user_budget_rejected():
    from litellm.constants import UI_SESSION_TOKEN_TEAM_ID

    data = GenerateKeyRequest(max_budget=600)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-ui-session",
        user_id="user-1",
        team_id=UI_SESSION_TOKEN_TEAM_ID,
        max_budget=1.0,
        user_max_budget=500.0,
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),  # test-quality-ok: helper reads proxy_server.prisma_client directly
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),  # test-quality-ok: helper reads proxy_server.user_api_key_cache directly
        patch("litellm.proxy.proxy_server.llm_router", None),  # test-quality-ok: helper reads proxy_server.llm_router directly
        patch("litellm.proxy.proxy_server.premium_user", False),  # test-quality-ok: helper reads proxy_server.premium_user directly
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "default_user_id"),  # test-quality-ok: helper reads proxy_server.litellm_proxy_admin_name directly
        patch(  # test-quality-ok: helper has no dependency injection seam for key persistence
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):
        mock_generate_key.return_value = {"key": "sk-test-key", "token_id": "token-id"}
        with pytest.raises((HTTPException, ProxyException)) as exc_info:
            await _common_key_generation_helper(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                team_table=None,
            )
        err = exc_info.value
        code = getattr(err, "status_code", None) or getattr(err, "code", None)
        msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
        assert str(code) == "400"
        assert "cannot exceed" in msg.lower()
        assert "500.0" in msg


@pytest.mark.asyncio
async def test_ghsa_q775_default_team_id_does_not_grant_session_token_exemption():
    """
    Security regression for GHSA-q775: the team-key exemption must key off the
    team_id the CALLER supplied, not one injected by default_key_generate_params.
    With default_key_generate_params.team_id set, a UI session token's personal-key
    request (no team_id) would otherwise have team_id auto-filled before the ceiling
    check, flipping is_ui_session_team_key to True and bypassing the ceiling. The
    request must still be rejected. Mirrors how _requested_max_budget is captured
    before defaults run.
    """
    from litellm.constants import UI_SESSION_TOKEN_TEAM_ID

    data = GenerateKeyRequest(max_budget=500)
    assert data.team_id is None
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-ui-session",
        user_id="user-1",
        team_id=UI_SESSION_TOKEN_TEAM_ID,
        max_budget=0.25,
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "default_user_id"),
        patch("litellm.default_key_generate_params", {"team_id": "injected-team"}),
    ):
        with pytest.raises((HTTPException, ProxyException)) as exc_info:
            await _common_key_generation_helper(
                data=data,
                user_api_key_dict=user_api_key_dict,
                litellm_changed_by=None,
                team_table=None,
            )
        err = exc_info.value
        code = getattr(err, "status_code", None) or getattr(err, "code", None)
        msg = str(getattr(err, "detail", "")) + str(getattr(err, "message", ""))
        assert str(code) == "400"
        assert "cannot exceed" in msg.lower()


@pytest.mark.asyncio
async def test_prepare_key_update_data_budget_duration_null_clears_fields():
    """
    When budget_duration is explicitly set to null, prepare_key_update_data
    should produce budget_duration=None and budget_reset_at=None so Prisma
    clears them in the DB.
    """
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=[],
        user_id="test-user",
        team_id=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(key="test-token", budget_duration=None)

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    assert "budget_duration" in result
    assert result["budget_duration"] is None
    assert "budget_reset_at" in result
    assert result["budget_reset_at"] is None


@pytest.mark.asyncio
async def test_prepare_key_update_data_budget_duration_not_sent_excluded():
    """
    When budget_duration is NOT sent in the request (unset), it should not
    appear in the result dict at all — the existing DB value stays unchanged.
    """
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=[],
        user_id="test-user",
        team_id=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(key="test-token", models=["gpt-4"])

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    assert "budget_duration" not in result
    assert "budget_reset_at" not in result


@pytest.mark.asyncio
async def test_prepare_key_update_data_budget_duration_valid_sets_reset():
    """
    When budget_duration is set to a valid duration string, both
    budget_duration and budget_reset_at should be populated.
    """
    existing_key = LiteLLM_VerificationToken(
        token="test-token",
        key_alias="test-key",
        models=[],
        user_id="test-user",
        team_id=None,
        metadata={},
    )

    update_request = UpdateKeyRequest(key="test-token", budget_duration="30d")

    result = await prepare_key_update_data(
        data=update_request, existing_key_row=existing_key
    )

    assert result["budget_duration"] == "30d"
    assert result["budget_reset_at"] is not None


@pytest.mark.asyncio
async def test_info_key_fn_includes_model_max_budget_usage(monkeypatch):
    """
    /key/info should include model_max_budget_usage showing current-period spend
    for each model that has a per-model budget configured.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_budget_test"
    model_max_budget = {
        "gpt-4o": {"budget_limit": 0.50, "time_period": "1d"},
    }

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    # A real cache seeded at the real counter key: the spend only comes back if
    # the endpoint computed virtual_key_spend:hashed_token_budget_test:gpt-4o:1d.
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        await _budget_cache({"virtual_key_spend:hashed_token_budget_test:gpt-4o:1d": 0.23}),
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-x"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": model_max_budget,
        "user_id": "user-x",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-budget-key",
    )

    result = await info_key_fn(
        key="sk-test-budget-key",
        user_api_key_dict=user_api_key_dict,
    )

    assert "model_max_budget_usage" in result["info"]
    usage = result["info"]["model_max_budget_usage"]
    assert usage["gpt-4o"]["current_spend"] == 0.23
    assert usage["gpt-4o"]["budget_limit"] == 0.50
    assert usage["gpt-4o"]["time_period"] == "1d"
    mock_prisma_client.db.query_raw.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_no_model_max_budget_skips_usage(monkeypatch):
    """Keys with no model_max_budget should not include model_max_budget_usage."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_no_budget"

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    mock_user_api_key_cache.async_get_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        mock_user_api_key_cache,
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-y"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": {},
        "user_id": "user-y",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-no-budget",
    )

    result = await info_key_fn(
        key="sk-test-no-budget",
        user_api_key_dict=user_api_key_dict,
    )

    assert "model_max_budget_usage" not in result["info"]
    mock_prisma_client.db.query_raw.assert_not_awaited()
    mock_user_api_key_cache.async_get_cache.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_v2_includes_model_max_budget_usage(monkeypatch):
    """/v2/key/info should include model_max_budget_usage for keys with per-model budgets."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        info_key_fn_v2,
    )

    test_key_token = "hashed_token_v2_test"
    model_max_budget = {"gpt-4o": {"budget_limit": 1.00, "time_period": "7d"}}

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    # A real cache seeded at the real counter key: the spend only comes back if
    # the endpoint computed virtual_key_spend:hashed_token_v2_test:gpt-4o:7d.
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        await _budget_cache({"virtual_key_spend:hashed_token_v2_test:gpt-4o:7d": 0.55}),
    )

    mock_key = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key.token = test_key_token
    mock_key.user_id = "user-v2"
    mock_key.team_id = None
    mock_key.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": model_max_budget,
        "user_id": "user-v2",
        "team_id": None,
        "litellm_budget_table": None,
    }
    mock_key.dict.return_value = mock_key.model_dump.return_value

    mock_prisma_client.get_data = AsyncMock(return_value=[mock_key])
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
    )

    result = await info_key_fn_v2(
        data=KeyRequest(keys=[test_key_token]),
        user_api_key_dict=user_api_key_dict,
    )

    assert len(result["info"]) == 1
    key_info = result["info"][0]
    assert "model_max_budget_usage" in key_info
    usage = key_info["model_max_budget_usage"]
    assert usage["gpt-4o"]["current_spend"] == 0.55
    assert usage["gpt-4o"]["budget_limit"] == 1.00
    assert usage["gpt-4o"]["time_period"] == "7d"
    mock_prisma_client.db.query_raw.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_budget_table_fallback(monkeypatch):
    """When model_max_budget is empty on the key but set in litellm_budget_table,
    /key/info should still populate model_max_budget_usage.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_budget_table_test"
    budget_table_model_max_budget = {
        "bedrock/anthropic.claude-opus-4": {"max_budget": 5, "budget_duration": "30d"},
    }

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    # A real cache seeded at the real counter key: the spend only comes back if
    # the endpoint computed virtual_key_spend:hashed_token_budget_table_test:bedrock/anthropic.claude-opus-4:30d.
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        await _budget_cache({"virtual_key_spend:hashed_token_budget_table_test:bedrock/anthropic.claude-opus-4:30d": 1.20}),
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-bt"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": {},
        "user_id": "user-bt",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": {
            "budget_id": "bt-123",
            "budget_duration": "30d",
            "budget_reset_at": "2026-07-01T00:00:00+00:00",
            "model_max_budget": budget_table_model_max_budget,
        },
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-bt-key",
    )

    result = await info_key_fn(
        key="sk-test-bt-key",
        user_api_key_dict=user_api_key_dict,
    )

    assert "model_max_budget_usage" in result["info"]
    usage = result["info"]["model_max_budget_usage"]
    assert usage["bedrock/anthropic.claude-opus-4"]["current_spend"] == 1.20
    assert usage["bedrock/anthropic.claude-opus-4"]["budget_limit"] == 5
    assert usage["bedrock/anthropic.claude-opus-4"]["time_period"] == "30d"
    mock_prisma_client.db.query_raw.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_v2_budget_table_fallback(monkeypatch):
    """When model_max_budget is empty on the key but set in litellm_budget_table,
    /v2/key/info should still populate model_max_budget_usage."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        info_key_fn_v2,
    )

    test_key_token = "hashed_token_v2_bt_test"
    budget_table_model_max_budget = {
        "bedrock/anthropic.claude-opus-4": {"max_budget": 5, "budget_duration": "30d"},
    }

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    # A real cache seeded at the real counter key: the spend only comes back if
    # the endpoint computed virtual_key_spend:hashed_token_v2_bt_test:bedrock/anthropic.claude-opus-4:30d.
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        await _budget_cache({"virtual_key_spend:hashed_token_v2_bt_test:bedrock/anthropic.claude-opus-4:30d": 2.50}),
    )

    mock_key = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key.token = test_key_token
    mock_key.user_id = "user-v2-bt"
    mock_key.team_id = None
    mock_key.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": {},
        "user_id": "user-v2-bt",
        "team_id": None,
        "litellm_budget_table": {
            "budget_id": "bt-456",
            "budget_duration": "30d",
            "budget_reset_at": "2026-07-01T00:00:00+00:00",
            "model_max_budget": budget_table_model_max_budget,
        },
    }
    mock_key.dict.return_value = mock_key.model_dump.return_value

    mock_prisma_client.get_data = AsyncMock(return_value=[mock_key])
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin-v2-bt",
    )

    result = await info_key_fn_v2(
        data=KeyRequest(keys=[test_key_token]),
        user_api_key_dict=user_api_key_dict,
    )

    assert len(result["info"]) == 1
    key_info = result["info"][0]
    assert "model_max_budget_usage" in key_info
    usage = key_info["model_max_budget_usage"]
    assert usage["bedrock/anthropic.claude-opus-4"]["current_spend"] == 2.50
    mock_prisma_client.db.query_raw.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_reports_budget_limits_usage(monkeypatch):
    """
    /key/info reports current-window spend per budget window under budget_limits_usage,
    keyed by budget_duration and read from the same counter enforcement uses, while
    budget_limits itself comes back exactly as stored.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_window_test"
    budget_limits = [
        {
            "reset_at": "2026-08-15T18:00:00+00:00",
            "max_budget": 2.0,
            "budget_duration": "1h",
        }
    ]

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    mock_get_current_spend = AsyncMock(return_value=0.73)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-w"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "budget_limits": [dict(w) for w in budget_limits],
        "user_id": "user-w",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-window-key",
    )

    result = await info_key_fn(
        key="sk-test-window-key",
        user_api_key_dict=user_api_key_dict,
    )

    assert result["info"]["budget_limits"] == budget_limits
    assert result["info"]["budget_limits_usage"] == {"1h": {"current_spend": 0.73}}

    mock_get_current_spend.assert_awaited_once()
    call_kwargs = mock_get_current_spend.await_args.kwargs
    assert call_kwargs["counter_key"] == f"spend:key:{test_key_token}:window:1h"
    assert call_kwargs["max_budget"] == 2.0
    assert call_kwargs["window_entity_type"] == "Key"
    assert call_kwargs["window_entity_id"] == test_key_token
    assert call_kwargs["window_duration"] == "1h"
    assert call_kwargs["window_start"] is not None


@pytest.mark.asyncio
async def test_info_key_fn_no_budget_limits_skips_spend_lookup(monkeypatch):
    """Keys without budget windows get no budget_limits_usage field and trigger no spend lookup."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_no_windows"

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    mock_get_current_spend = AsyncMock(return_value=0.0)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-nw"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "budget_limits": None,
        "user_id": "user-nw",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-test-no-window-key",
    )

    result = await info_key_fn(
        key="sk-test-no-window-key",
        user_api_key_dict=user_api_key_dict,
    )

    assert result["info"]["budget_limits"] is None
    assert "budget_limits_usage" not in result["info"]
    mock_get_current_spend.assert_not_awaited()


@pytest.mark.asyncio
async def test_info_key_fn_v2_reports_budget_limits_usage(monkeypatch):
    """/v2/key/info reports budget_limits_usage per window and leaves budget_limits as stored."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import KeyRequest, LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        info_key_fn_v2,
    )

    test_key_token = "hashed_token_v2_window_test"
    budget_limits = [
        {
            "reset_at": "2026-08-15T18:00:00+00:00",
            "max_budget": 2.0,
            "budget_duration": "1h",
        },
        {
            "reset_at": "2026-08-16T00:00:00+00:00",
            "max_budget": 20.0,
            "budget_duration": "1d",
        },
    ]

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    mock_get_current_spend = AsyncMock(return_value=1.25)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    mock_key = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key.token = test_key_token
    mock_key.user_id = "user-v2-w"
    mock_key.team_id = None
    mock_key.model_dump.return_value = {
        "token": test_key_token,
        "budget_limits": [dict(w) for w in budget_limits],
        "user_id": "user-v2-w",
        "team_id": None,
        "litellm_budget_table": None,
    }
    mock_key.dict.return_value = mock_key.model_dump.return_value

    mock_prisma_client.get_data = AsyncMock(return_value=[mock_key])

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin-v2-w",
    )

    result = await info_key_fn_v2(
        data=KeyRequest(keys=[test_key_token]),
        user_api_key_dict=user_api_key_dict,
    )

    assert len(result["info"]) == 1
    assert result["info"][0]["budget_limits"] == budget_limits
    assert result["info"][0]["budget_limits_usage"] == {
        "1h": {"current_spend": 1.25},
        "1d": {"current_spend": 1.25},
    }
    assert mock_get_current_spend.await_count == 2
    counter_keys = {
        call.kwargs["counter_key"] for call in mock_get_current_spend.await_args_list
    }
    assert counter_keys == {
        f"spend:key:{test_key_token}:window:1h",
        f"spend:key:{test_key_token}:window:1d",
    }
    assert {
        call.kwargs["window_duration"] for call in mock_get_current_spend.await_args_list
    } == {"1h", "1d"}


@pytest.mark.asyncio
async def test_build_budget_limits_usage_json_string_input(monkeypatch):
    """budget_limits stored as a JSON string is parsed and reported per window."""
    import json as json_module
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_budget_limits_usage,
    )

    mock_get_current_spend = AsyncMock(return_value=0.5)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    raw = json_module.dumps(
        [{"budget_duration": "1h", "max_budget": 2.0, "reset_at": None}]
    )
    result = await _build_budget_limits_usage(budget_limits=raw, api_key_hash="hash-1")

    assert result == {"1h": {"current_spend": 0.5}}
    mock_get_current_spend.assert_awaited_once()


@pytest.mark.asyncio
async def test_build_budget_limits_usage_empty_windows_returns_none(monkeypatch):
    """A key with no windows (None, [], or "[]") returns None so the field is left off; no spend lookup runs."""
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_budget_limits_usage,
    )

    mock_get_current_spend = AsyncMock(return_value=0.0)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    for stored in (None, [], "[]"):
        assert await _build_budget_limits_usage(budget_limits=stored, api_key_hash="hash-1") is None
    mock_get_current_spend.assert_not_awaited()


@pytest.mark.asyncio
async def test_build_budget_limits_usage_window_without_max_budget(monkeypatch):
    """A window with only budget_duration still reports current_spend, read without a budget ceiling."""
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_budget_limits_usage,
    )

    mock_get_current_spend = AsyncMock(return_value=0.75)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    result = await _build_budget_limits_usage(
        budget_limits=[{"budget_duration": "2d"}], api_key_hash="hash-no-max"
    )

    assert result == {"2d": {"current_spend": 0.75}}
    call_kwargs = mock_get_current_spend.await_args.kwargs
    assert call_kwargs["counter_key"] == "spend:key:hash-no-max:window:2d"
    assert call_kwargs["window_duration"] == "2d"
    assert call_kwargs["max_budget"] is None


@pytest.mark.asyncio
async def test_build_budget_limits_usage_pydantic_windows(monkeypatch):
    """BudgetLimitEntry windows (the shape UserAPIKeyAuth carries) are dumped to dicts and reported."""
    from unittest.mock import AsyncMock

    from litellm.models.team import BudgetLimitEntry
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_budget_limits_usage,
    )

    mock_get_current_spend = AsyncMock(return_value=1.0)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.get_current_spend", mock_get_current_spend
    )

    result = await _build_budget_limits_usage(
        budget_limits=[BudgetLimitEntry(budget_duration="7d", max_budget=10.0)],
        api_key_hash="hash-2",
    )

    assert result == {"7d": {"current_spend": 1.0}}
    call_kwargs = mock_get_current_spend.await_args.kwargs
    assert call_kwargs["counter_key"] == "spend:key:hash-2:window:7d"
    assert call_kwargs["window_duration"] == "7d"
    assert call_kwargs["max_budget"] == 10.0


@pytest.mark.asyncio
async def test_info_key_fn_reads_the_configured_budget_model_key(monkeypatch):
    """/key/info reads the one counter enforcement reads: the configured budget model.

    It used to probe a second, provider-stripped key because the counter was
    written under the request model instead, which is what let a key report zero
    usage while being blocked at 422.
    """
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LiteLLM_VerificationToken
    from litellm.proxy.management_endpoints.key_management_endpoints import info_key_fn

    test_key_token = "hashed_token_prefix_test"
    model_max_budget = {
        "openai/gpt-4o": {"budget_limit": 2.00, "time_period": "7d"},
    }

    mock_prisma_client = AsyncMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    mock_user_api_key_cache = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache
    )
    # A real cache seeded at the real counter key: the spend only comes back if
    # the endpoint computed virtual_key_spend:hashed_token_prefix_test:openai/gpt-4o:7d.
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.model_max_budget_limiter.dual_cache",
        await _budget_cache({"virtual_key_spend:hashed_token_prefix_test:openai/gpt-4o:7d": 0.75}),
    )

    mock_key_info = MagicMock(spec=LiteLLM_VerificationToken)
    mock_key_info.token = test_key_token
    mock_key_info.object_permission_id = None
    mock_key_info.user_id = "user-prefix"
    mock_key_info.team_id = None
    mock_key_info.litellm_budget_table = None
    mock_key_info.model_dump.return_value = {
        "token": test_key_token,
        "model_max_budget": model_max_budget,
        "user_id": "user-prefix",
        "team_id": None,
        "object_permission_id": None,
        "litellm_budget_table": None,
    }
    mock_key_info.dict.return_value = mock_key_info.model_dump.return_value

    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=mock_key_info
    )
    mock_prisma_client.db.query_raw = AsyncMock()

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-prefix-test",
    )

    result = await info_key_fn(
        key="sk-prefix-test",
        user_api_key_dict=user_api_key_dict,
    )

    assert "model_max_budget_usage" in result["info"]
    usage = result["info"]["model_max_budget_usage"]
    assert usage["openai/gpt-4o"]["current_spend"] == 0.75


async def _budget_cache(seeded):
    """A real DualCache holding spend at the given LITERAL counter keys.

    The keys are spelled out in full on purpose. Seeding via
    model_budget_spend_cache_key would move the seed and the read together, so
    any change to the key format would still match itself and these tests could
    never fail, which is the exact bug they exist to catch.
    """
    from litellm.caching.caching import DualCache

    cache = DualCache()
    for key, spend in seeded.items():
        await cache.async_set_cache(key, spend)
    return cache


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_no_cache_returns_empty():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={"gpt-4o": {"budget_limit": 1.0, "time_period": "1d"}},
        user_api_key_cache=None,
    )
    assert result == {}


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_reads_current_cache_window():
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    cache = await _budget_cache({"virtual_key_spend:some-hash:gpt-4o:30d": 0.30})

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={"gpt-4o": {"budget_limit": 1.0, "time_period": "30d"}},
        user_api_key_cache=cache,
    )

    # 0.30 comes back only if the key matched virtual_key_spend:some-hash:gpt-4o:30d.
    assert result["gpt-4o"]["current_spend"] == 0.30


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_no_duration_in_budget_returns_empty():
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    mock_user_api_key_cache = AsyncMock()
    mock_user_api_key_cache.async_get_cache = AsyncMock()

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={"gpt-4o": {"budget_limit": 1.0}},
        user_api_key_cache=mock_user_api_key_cache,
    )
    assert result == {}
    mock_user_api_key_cache.async_get_cache.assert_not_awaited()


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_skips_model_without_duration():
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    cache = await _budget_cache({"virtual_key_spend:some-hash:gpt-4o:1d": 0.10})

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={
            "gpt-4o": {"budget_limit": 1.0, "time_period": "1d"},
            "gpt-3.5-turbo": {"budget_limit": 0.5},
        },
        user_api_key_cache=cache,
    )
    assert result["gpt-4o"]["current_spend"] == 0.10
    assert "gpt-3.5-turbo" not in result


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_unparseable_duration_skipped():
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    mock_user_api_key_cache = AsyncMock()
    mock_user_api_key_cache.async_get_cache = AsyncMock()

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={
            "gpt-4o": {"budget_limit": 1.0, "budget_duration": "not-valid"}
        },
        user_api_key_cache=mock_user_api_key_cache,
    )
    assert result == {}
    mock_user_api_key_cache.async_get_cache.assert_not_awaited()


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_invalid_budget_config_skipped():
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    cache = await _budget_cache({"virtual_key_spend:some-hash:gpt-3.5-turbo:7d": 0.20})

    result = await _build_model_max_budget_usage(
        api_key_hash="some-hash",
        model_max_budget={
            "gpt-4o": {"max_budget": "not-a-number", "budget_duration": "1d"},
            "gpt-3.5-turbo": {"budget_limit": 0.5, "time_period": "7d"},
        },
        user_api_key_cache=cache,
    )
    assert "gpt-4o" not in result
    assert result["gpt-3.5-turbo"]["current_spend"] == 0.20


@pytest.mark.asyncio
async def test_build_model_max_budget_usage_reads_only_the_configured_model_key():
    """One lookup, at the configured budget model.

    The counter is written under the name the operator configured, so probing a
    provider-stripped variant would read a key nothing writes.
    """
    from unittest.mock import AsyncMock

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_model_max_budget_usage,
    )

    cache = await _budget_cache({"virtual_key_spend:test-hash:openai/gpt-4o:7d": 0.55})

    result = await _build_model_max_budget_usage(
        api_key_hash="test-hash",
        model_max_budget={"openai/gpt-4o": {"budget_limit": 2.0, "time_period": "7d"}},
        user_api_key_cache=cache,
    )

    # Seeded only under the configured name, so a provider-stripped probe reads 0.0.
    assert result["openai/gpt-4o"]["current_spend"] == 0.55


def test_list_keys_substring_matching_param_defaults_to_false():
    """Regression guard: /key/list matched user_id/key_alias exactly before
    substring search was added (commit 33bd570d5e). The substring_matching query
    param must default to False so an absent param yields exact matching."""
    import inspect

    param = inspect.signature(list_keys).parameters["substring_matching"]
    assert getattr(param.default, "default", param.default) is False


async def _list_keys_capture_helper_kwargs(user_api_key_dict, **list_kwargs):
    from unittest.mock import Mock, patch

    from litellm.proxy._types import LiteLLM_UserTable

    mock_user_info = LiteLLM_UserTable(
        user_id=user_api_key_dict.user_id,
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )
    helper = AsyncMock(
        return_value={"keys": [], "total_count": 0, "current_page": 1, "total_pages": 0}
    )
    with patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()):
        with patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_list_check",
            return_value=mock_user_info,
        ):
            with patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.list_key_helper",
                helper,
            ):
                await list_keys(
                    request=Mock(),
                    user_api_key_dict=user_api_key_dict,
                    status=None,
                    **list_kwargs,
                )
    return helper.call_args.kwargs


@pytest.mark.asyncio
async def test_list_keys_admin_exact_by_default():
    """Security regression: an admin calling /key/list with an exact user_id and
    no substring_matching flag must get exact matching, so an integration scoping
    to one user with an admin key never receives other users' keys."""
    admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin-1")
    kwargs = await _list_keys_capture_helper_kwargs(
        admin, user_id="alice", substring_matching=False
    )
    assert kwargs["user_id"] == "alice"
    assert kwargs["use_substring_matching"] is False


@pytest.mark.asyncio
async def test_list_keys_admin_substring_opt_in():
    """An admin may opt back into substring matching (dashboard search)."""
    admin = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin-1")
    kwargs = await _list_keys_capture_helper_kwargs(
        admin, user_id="alice", substring_matching=True
    )
    assert kwargs["use_substring_matching"] is True


@pytest.mark.asyncio
async def test_list_keys_non_admin_cannot_opt_into_substring():
    """user_id substring matching is admin-only: a non-admin requesting it still
    gets exact matching, scoped to their own user_id."""
    user = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    kwargs = await _list_keys_capture_helper_kwargs(
        user, user_id=None, substring_matching=True
    )
    assert kwargs["use_substring_matching"] is False
    assert kwargs["user_id"] == "alice"


def _prisma_where_matches(row, where):
    for field, expected in where.items():
        if field == "AND":
            if not all(_prisma_where_matches(row, child) for child in expected):
                return False
        elif field == "OR":
            if not any(_prisma_where_matches(row, child) for child in expected):
                return False
        elif isinstance(expected, dict):
            value = getattr(row, field)
            if "in" in expected and value not in expected["in"]:
                return False
            if "not" in expected and value == expected["not"]:
                return False
            if "contains" in expected:
                haystack, needle = value or "", expected["contains"]
                if expected.get("mode") == "insensitive":
                    haystack, needle = haystack.lower(), needle.lower()
                if needle not in haystack:
                    return False
        elif getattr(row, field) != expected:
            return False
    return True


class _InMemoryVerificationTokenTable:
    def __init__(self, rows):
        self.rows = rows

    async def find_many(self, where, **kwargs):
        return [row for row in self.rows if _prisma_where_matches(row, where)]

    async def count(self, where):
        return len(await self.find_many(where))


def _team_key(token, key_alias, user_id):
    return LiteLLM_VerificationToken(token=token, key_alias=key_alias, user_id=user_id, team_id="team-a")


_TEAM_A_KEYS = (
    _team_key("tok-alice-first", "app_llmhub_first.last", "alice"),
    _team_key("tok-alice-other", "alice_other_key", "alice"),
    _team_key("tok-bob-first", "bob_First_key", "bob"),
    _team_key("tok-svc-first", "service_first_key", None),
)


def _list_team_a_keys_as(user_role, members_with_roles, query):
    from fastapi import FastAPI

    from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
    from litellm.proxy.management_endpoints.key_management_endpoints import router

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken = _InMemoryVerificationTokenTable(_TEAM_A_KEYS)
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(user_id="alice", teams=["team-a"], organization_memberships=[])
    )
    mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(
        return_value=[LiteLLM_TeamTable(team_id="team-a", members_with_roles=members_with_roles)]
    )
    test_app = FastAPI()
    test_app.include_router(router)
    test_app.dependency_overrides[user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=user_role, user_id="alice")
    with patch(  # test-quality-ok: /key/list reads the prisma client from the proxy_server module global, no injection point
        "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
    ):
        response = TestClient(test_app).get(
            f"/key/list?team_id=team-a&include_team_keys=true&include_created_by_keys=true&{query}"
        )
    assert response.status_code == 200, response.text
    return sorted(response.json()["keys"])


_ALICE_TEAM_ADMIN = [Member(user_id="alice", role="admin"), Member(user_id="bob", role="user")]
_ALICE_TEAM_MEMBER = [Member(user_id="alice", role="user"), Member(user_id="bob", role="user")]


@pytest.mark.parametrize(
    "user_role",
    [LitellmUserRoles.INTERNAL_USER, LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, LitellmUserRoles.TEAM],
)
def test_list_keys_team_admin_key_alias_substring_returns_every_matching_team_key(user_role):
    keys = _list_team_a_keys_as(user_role, _ALICE_TEAM_ADMIN, "key_alias=first&substring_matching=true")
    assert keys == ["tok-alice-first", "tok-bob-first", "tok-svc-first"]


def test_list_keys_team_member_key_alias_substring_stays_within_own_visibility():
    keys = _list_team_a_keys_as(
        LitellmUserRoles.INTERNAL_USER, _ALICE_TEAM_MEMBER, "key_alias=first&substring_matching=true"
    )
    assert keys == ["tok-alice-first", "tok-svc-first"]


def test_list_keys_key_alias_stays_exact_without_substring_matching():
    assert _list_team_a_keys_as(LitellmUserRoles.INTERNAL_USER, _ALICE_TEAM_ADMIN, "key_alias=first") == []
    assert _list_team_a_keys_as(
        LitellmUserRoles.INTERNAL_USER, _ALICE_TEAM_ADMIN, "key_alias=app_llmhub_first.last"
    ) == ["tok-alice-first"]


@pytest.mark.asyncio
async def test_list_keys_search_is_honored_for_non_admin():
    """LIT-4741: unlike substring_matching, `search` is not admin-gated. A non-admin's
    search reaches the helper while their own-user scoping stays in place."""
    user = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    kwargs = await _list_keys_capture_helper_kwargs(user, user_id=None, search="key-id-123")
    assert kwargs["search"] == "key-id-123"
    assert kwargs["user_id"] == "alice"


@pytest.mark.asyncio
async def test_cli_session_token_delegation_ceiling_blocked_by_team_budget():
    team = LiteLLM_TeamTableCachedObj(team_id="team-1", max_budget=50.0)
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(max_budget=1000.0),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=team,
        )
    assert exc_info.value.status_code == 400
    assert "max_budget" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_cli_session_token_delegation_allowed_within_team_budget():
    team = LiteLLM_TeamTableCachedObj(team_id="team-1", max_budget=50.0)
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=GenerateKeyRequest(max_budget=25.0),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=team,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_regular_unlimited_user_delegation_ceiling_not_applied():
    team = LiteLLM_TeamTableCachedObj(team_id="team-1", max_budget=50.0)
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=False,
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=GenerateKeyRequest(max_budget=1000.0),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=team,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_cli_session_token_personal_key_with_budget_blocked():
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(max_budget=1000.0),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,  # no team in request = personal key
        )
    assert exc_info.value.status_code == 400
    assert "team_id" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_cli_session_token_personal_key_without_budget_allowed():
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=GenerateKeyRequest(max_budget=None),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,  # no team in request = personal key, but no explicit budget
        )
    assert result is not None


@pytest.mark.asyncio
async def test_budget_limits_window_cannot_exceed_caller_max_budget(monkeypatch):
    """A non-admin caller may not set a `budget_limits` window above
    their own `max_budget`."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=10.0,
    )
    request = GenerateKeyRequest(
        budget_limits=[
            {"budget_duration": "1d", "max_budget": 1_000_000.0},
        ],
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 400
    assert "budget_limits" in str(exc_info.value.detail)
    assert "1000000" in str(exc_info.value.detail).replace(",", "")


@pytest.mark.asyncio
async def test_budget_limits_window_within_caller_max_budget_allowed(monkeypatch):
    """Counterpart: a window within the caller's ceiling must still pass."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 25.0}],
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_budget_limits_admin_unrestricted(monkeypatch):
    """Proxy admin can set any window budget regardless of their own max_budget."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-1",
        max_budget=10.0,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 1_000_000.0}],
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "admin-1"},
    ):
        result = await _common_key_generation_helper(
            data=request,
            user_api_key_dict=admin,
            litellm_changed_by=None,
            team_table=None,
        )
    assert result is not None


@pytest.mark.asyncio
@pytest.mark.parametrize("non_finite", [float("nan"), float("inf"), float("-inf")])
async def test_budget_limits_window_non_finite_rejected_for_non_admin(monkeypatch, non_finite):
    """A non-admin caller submitting a non-finite `budget_limits` window
    gets 400. The finite-number invariant applies before role / ceiling
    checks."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=10.0,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": non_finite}],
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 400
    assert "finite" in str(exc_info.value.detail)


@pytest.mark.asyncio
@pytest.mark.parametrize("non_finite", [float("nan"), float("inf"), float("-inf")])
async def test_budget_limits_window_non_finite_rejected_for_admin(monkeypatch, non_finite):
    """The finite-number invariant applies to every caller including
    proxy admin."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-1",
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": non_finite}],
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=admin,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 400
    assert "finite" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_budget_limits_session_token_personal_key_rejected(monkeypatch):
    """A CLI session token caller may not set `budget_limits` on a
    personal key (no `team_id`). Mirrors the scalar `max_budget` guard."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        is_session_token=True,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 1_000_000.0}],
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 400
    assert "session token" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_budget_limits_session_token_team_key_uses_team_ceiling(monkeypatch):
    """A CLI session token acting on a team key uses the team's
    `max_budget` as the ceiling; values within it are permitted."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    team = LiteLLM_TeamTableCachedObj(team_id="team-1", max_budget=50.0)
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 25.0}],
        team_id="team-1",
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=team,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_budget_limits_session_token_team_key_over_team_budget_rejected(monkeypatch):
    """Same shape, but window exceeds the team's `max_budget`."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    team = LiteLLM_TeamTableCachedObj(team_id="team-1", max_budget=50.0)
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        team_id="team-1",
        is_session_token=True,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 1_000_000.0}],
        team_id="team-1",
    )
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=team,
        )
    assert exc_info.value.status_code == 400
    assert "cannot exceed" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_budget_limits_session_token_personal_key_admin_unaffected(monkeypatch):
    """A proxy admin using a session token is exempt from the personal-key
    reject; the role short-circuit runs first."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-1",
        is_session_token=True,
    )
    request = GenerateKeyRequest(
        budget_limits=[{"budget_duration": "1d", "max_budget": 1_000_000.0}],
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "admin-1"},
    ):
        result = await _common_key_generation_helper(
            data=request,
            user_api_key_dict=admin,
            litellm_changed_by=None,
            team_table=None,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_permissions_field_rejected_for_non_admin(monkeypatch):
    """A non-admin caller may not set the `permissions` field on a key
    they create."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    request = GenerateKeyRequest(permissions={"get_spend_routes": True})
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 403
    assert "permissions" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_permissions_empty_default_allowed_for_non_admin(monkeypatch):
    """
    The empty `{}` default on GenerateKeyRequest.permissions must continue
    to pass for non-admin callers; only a non-empty dict triggers the gate.
    """
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "user-1"},
    ):
        result = await _common_key_generation_helper(
            data=GenerateKeyRequest(),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_permissions_admin_can_set_any(monkeypatch):
    """Proxy admin can still set `permissions` on a key."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        user_id="admin-1",
    )
    request = GenerateKeyRequest(permissions={"get_spend_routes": True})
    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
        new_callable=AsyncMock,
        return_value={"key": "sk-test", "expires": None, "user_id": "admin-1"},
    ):
        result = await _common_key_generation_helper(
            data=request,
            user_api_key_dict=admin,
            litellm_changed_by=None,
            team_table=None,
        )
    assert result is not None


@pytest.mark.asyncio
async def test_permissions_explicit_empty_rejected_for_non_admin_on_generate(monkeypatch):
    """`_common_key_generation_helper` rejects a non-admin when
    `permissions` is present in the request body, even as `{}`. Omit-default
    stays allowed; that carve-out lives in
    `test_permissions_empty_default_allowed_for_non_admin`."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    request = GenerateKeyRequest(permissions={})
    assert "permissions" in request.model_fields_set
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 403
    assert "permissions" in str(exc_info.value.detail)


def _make_personal_key_row_for_alice():
    return MagicMock(
        token="hashed_alice_personal_key",
        user_id="alice",
        team_id=None,
        created_by="alice",
        max_budget=None,
        organization_id=None,
        project_id=None,
    )


def _make_alice_internal_user():
    return UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-alice",
        user_id="alice",
    )


@pytest.mark.asyncio
async def test_update_key_non_admin_permissions_non_empty_rejected(monkeypatch):
    """`_validate_update_key_data` rejects a non-admin when `permissions`
    is present in the request body (personal-key fast-path caller)."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data = UpdateKeyRequest(
        key="sk-alice-personal",
        permissions={"get_spend_routes": True},
    )

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=_make_personal_key_row_for_alice(),
            user_api_key_dict=_make_alice_internal_user(),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "permissions" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_non_admin_permissions_explicit_empty_rejected(monkeypatch):
    """`_validate_update_key_data` rejects a non-admin when `permissions`
    is present as `{}` in the request body. The value matches the model
    default but `model_fields_set` distinguishes the two."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data = UpdateKeyRequest(
        key="sk-alice-personal",
        permissions={},
    )
    assert "permissions" in data.model_fields_set

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=_make_personal_key_row_for_alice(),
            user_api_key_dict=_make_alice_internal_user(),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "permissions" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_non_admin_permissions_explicit_null_rejected(monkeypatch):
    """`_validate_update_key_data` rejects a non-admin when `permissions`
    is present as `null` in the request body."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data = UpdateKeyRequest(
        key="sk-alice-personal",
        permissions=None,
    )
    assert "permissions" in data.model_fields_set

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=_make_personal_key_row_for_alice(),
            user_api_key_dict=_make_alice_internal_user(),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "permissions" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_non_admin_omits_permissions_succeeds(monkeypatch):
    """`_validate_update_key_data` accepts a non-admin owner when
    `permissions` is absent from the request body (personal-key fast path
    on an unrelated field)."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data = UpdateKeyRequest(key="sk-alice-personal", tpm_limit=42)
    assert "permissions" not in data.model_fields_set

    await _validate_update_key_data(
        data=data,
        existing_key_row=_make_personal_key_row_for_alice(),
        user_api_key_dict=_make_alice_internal_user(),
        llm_router=None,
        premium_user=True,
        prisma_client=mock_prisma_client,
        user_api_key_cache=MagicMock(),
    )


@pytest.mark.asyncio
async def test_update_key_admin_can_set_permissions(monkeypatch):
    """`_validate_update_key_data` accepts a PROXY_ADMIN caller for every
    shape of `permissions` in the request body."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin-1",
    )
    for permissions_value in ({"get_spend_routes": True}, {}, None):
        data = UpdateKeyRequest(
            key="sk-alice-personal",
            permissions=permissions_value,
        )
        await _validate_update_key_data(
            data=data,
            existing_key_row=_make_personal_key_row_for_alice(),
            user_api_key_dict=admin,
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )


@pytest.mark.asyncio
async def test_regenerate_key_non_admin_permissions_rejected(monkeypatch):
    """`regenerate_key_fn` rejects a non-admin when `permissions` is
    present in the request body, before any DB work."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    data = RegenerateKeyRequest(
        key="sk-alice-personal",
        permissions={"get_spend_routes": True},
    )

    with pytest.raises(ProxyException) as exc:
        await regenerate_key_fn(
            key=None,
            data=data,
            user_api_key_dict=_make_alice_internal_user(),
            litellm_changed_by=None,
        )
    assert int(exc.value.code) == 403
    assert "permissions" in str(exc.value.message)


@pytest.mark.asyncio
async def test_regenerate_key_non_admin_permissions_explicit_empty_rejected(monkeypatch):
    """`regenerate_key_fn` rejects a non-admin when `permissions` is
    present as `{}` in the request body."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)

    data = RegenerateKeyRequest(key="sk-alice-personal", permissions={})
    assert "permissions" in data.model_fields_set

    with pytest.raises(ProxyException) as exc:
        await regenerate_key_fn(
            key=None,
            data=data,
            user_api_key_dict=_make_alice_internal_user(),
            litellm_changed_by=None,
        )
    assert int(exc.value.code) == 403
    assert "permissions" in str(exc.value.message)


@pytest.mark.asyncio
async def test_regenerate_key_non_admin_permissions_rejected_before_enterprise_gate(monkeypatch):
    """`regenerate_key_fn` runs `_check_permissions_caller_permission`
    before the `premium_user` check, so a non-premium proxy still returns
    the permissions rejection (403) rather than the enterprise-license
    error (500) when a non-admin sends `permissions`."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)

    data = RegenerateKeyRequest(
        key="sk-alice-personal",
        permissions={"get_spend_routes": True},
    )

    with pytest.raises(ProxyException) as exc:
        await regenerate_key_fn(
            key=None,
            data=data,
            user_api_key_dict=_make_alice_internal_user(),
            litellm_changed_by=None,
        )
    assert int(exc.value.code) == 403
    assert "permissions" in str(exc.value.message)
    assert "Enterprise" not in str(exc.value.message)


@pytest.mark.asyncio
async def test_generate_key_non_admin_disable_global_guardrails_rejected(monkeypatch):
    """`_common_key_generation_helper` rejects a non-admin setting
    `disable_global_guardrails` on the request body."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    request = GenerateKeyRequest(disable_global_guardrails=True)
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 403
    assert "disable_global_guardrails" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_generate_key_non_admin_metadata_disable_global_guardrails_rejected(monkeypatch):
    """`_common_key_generation_helper` rejects a non-admin smuggling
    `disable_global_guardrails` under `metadata`."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        None,
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )
    request = GenerateKeyRequest(metadata={"disable_global_guardrails": True})
    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=request,
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 403
    assert "disable_global_guardrails" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_generate_key_non_admin_server_default_guardrail_flag_not_treated_as_requested(monkeypatch):
    """An admin-configured `default_key_generate_params.metadata` containing
    `disable_global_guardrails: true` must not 403 a non-admin who sent no flag;
    only caller-sent metadata counts as requesting the opt-out."""
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.litellm.default_key_generate_params",
        {"metadata": {"disable_global_guardrails": True}},
        raising=False,
    )
    caller = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user-1",
        max_budget=100.0,
    )

    raised: Exception | None = None
    try:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(team_id="team-1", models=["gpt-4o"]),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    except Exception as exc:
        raised = exc
    assert not (isinstance(raised, HTTPException) and "disable_global_guardrails" in str(raised.detail)), raised

    with pytest.raises(HTTPException) as exc_info:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                team_id="team-1",
                models=["gpt-4o"],
                metadata={"disable_global_guardrails": True},
            ),
            user_api_key_dict=caller,
            litellm_changed_by=None,
            team_table=None,
        )
    assert exc_info.value.status_code == 403
    assert "disable_global_guardrails" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_update_key_non_admin_disable_global_guardrails_rejected(monkeypatch):
    """`_validate_update_key_data` rejects a non-admin when
    `disable_global_guardrails` is true in the request body."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    data = UpdateKeyRequest(
        key="sk-alice-personal",
        disable_global_guardrails=True,
    )

    with pytest.raises(HTTPException) as exc:
        await _validate_update_key_data(
            data=data,
            existing_key_row=_make_personal_key_row_for_alice(),
            user_api_key_dict=_make_alice_internal_user(),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    assert exc.value.status_code == 403
    assert "disable_global_guardrails" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_non_admin_resending_stored_disable_global_guardrails_allowed(monkeypatch):
    """`_validate_update_key_data` must not 403 when a non-admin edit form
    re-sends `metadata.disable_global_guardrails` that is already stored on
    the key (the Admin UI edit form round-trips the whole metadata JSON)."""
    mock_prisma_client = AsyncMock()
    mock_prisma_client.jsonify_object = lambda data: data
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    existing_key_row = _make_personal_key_row_for_alice()
    existing_key_row.metadata = {"disable_global_guardrails": True}
    data = UpdateKeyRequest(
        key="sk-alice-personal",
        metadata={"disable_global_guardrails": True, "x": 1},
    )

    raised: HTTPException | None = None
    try:
        await _validate_update_key_data(
            data=data,
            existing_key_row=existing_key_row,
            user_api_key_dict=_make_alice_internal_user(),
            llm_router=None,
            premium_user=True,
            prisma_client=mock_prisma_client,
            user_api_key_cache=MagicMock(),
        )
    except HTTPException as exc:
        raised = exc
    assert raised is None or "disable_global_guardrails" not in str(raised.detail)


@pytest.mark.asyncio
async def test_regenerate_key_non_admin_disable_global_guardrails_rejected(monkeypatch):
    """`regenerate_key_fn` rejects a non-admin setting
    `disable_global_guardrails` once the stored key row is loaded (the
    already-stored exemption check needs the row's metadata)."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        regenerate_key_fn,
    )

    existing_key = _make_regenerate_existing_key()
    mock_prisma_client = AsyncMock()
    mock_repo = MagicMock()
    mock_repo.table.find_unique = AsyncMock(return_value=existing_key)

    data = RegenerateKeyRequest(
        key="sk-alice-personal",
        disable_global_guardrails=True,
    )

    with (
        patch("litellm.proxy.proxy_server.premium_user", True),
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.VerificationTokenRepository",
            return_value=mock_repo,
        ),
        pytest.raises(ProxyException) as exc,
    ):
        await regenerate_key_fn(
            key=None,
            data=data,
            user_api_key_dict=_make_alice_internal_user(),
            litellm_changed_by=None,
        )
    assert int(exc.value.code) == 403
    assert "disable_global_guardrails" in str(exc.value.message)


def test_generate_key_helper_fn_accepts_per_tag_rate_limits():
    """
    Regression: new_user / SSO sign-in forward NewUserRequest fields to
    generate_key_helper_fn via `**data_json`. The per-tag limit field must be
    an accepted kwarg, otherwise user creation 500s with
    "generate_key_helper_fn() got an unexpected keyword argument 'tag_rpm_limit'".
    """
    params = inspect.signature(generate_key_helper_fn).parameters
    assert "tag_rpm_limit" in params

    # The field exists on the request model that new_user forwards via **data_json.
    assert "tag_rpm_limit" in NewUserRequest.model_fields

    # Binding the per-tag kwarg must not raise an unexpected-keyword TypeError.
    inspect.signature(generate_key_helper_fn).bind_partial(
        request_type="user",
        tag_rpm_limit={"cell-1": 5},
    )


def _find_expires_clauses(node):
    """Recursively collect every value keyed 'expires' anywhere in a Prisma where dict."""
    found = []
    if isinstance(node, dict):
        for key, value in node.items():
            if key == "expires":
                found.append(value)
            else:
                found.extend(_find_expires_clauses(value))
    elif isinstance(node, list):
        for item in node:
            found.extend(_find_expires_clauses(item))
    return found


def test_build_expires_where_clause_expired_shape():
    """'expired' must exclude never-expiring (NULL) keys and match expires < now."""
    from datetime import datetime, timezone

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_expires_where_clause,
    )

    now = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
    assert _build_expires_where_clause("expired", now) == {
        "AND": [{"expires": {"not": None}}, {"expires": {"lt": now}}]
    }


def test_build_expires_where_clause_active_shape():
    """'active' must include never-expiring (NULL) keys and match expires >= now."""
    from datetime import datetime, timezone

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_expires_where_clause,
    )

    now = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
    assert _build_expires_where_clause("active", now) == {
        "OR": [{"expires": None}, {"expires": {"gte": now}}]
    }


def test_build_key_filter_conditions_expired_applies_lt_clause():
    """expires_filter='expired' ANDs in a not-NULL + lt(now) constraint."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = _build_key_filter_conditions(
        user_id="u1",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        expires_filter="expired",
    )

    clauses = _find_expires_clauses(where)
    assert {"not": None} in clauses
    lt_clauses = [c for c in clauses if isinstance(c, dict) and "lt" in c]
    assert len(lt_clauses) == 1
    assert "gte" not in str(clauses)


def test_build_key_filter_conditions_active_applies_gte_and_null():
    """expires_filter='active' ANDs in a NULL-or-gte(now) constraint."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = _build_key_filter_conditions(
        user_id="u1",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        expires_filter="active",
    )

    clauses = _find_expires_clauses(where)
    assert None in clauses
    gte_clauses = [c for c in clauses if isinstance(c, dict) and "gte" in c]
    assert len(gte_clauses) == 1
    assert "lt" not in str(clauses)


def test_build_key_filter_conditions_no_expires_filter_omits_clause():
    """Default (no expires_filter) must not add any expires constraint — preserves existing callers."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = _build_key_filter_conditions(
        user_id="u1",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
    )

    assert _find_expires_clauses(where) == []


def test_build_key_filter_conditions_invalid_expires_filter_omits_clause():
    """An unrecognized expires_filter value is ignored, not applied blindly."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    where = _build_key_filter_conditions(
        user_id="u1",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        expires_filter="garbage",
    )

    assert _find_expires_clauses(where) == []


def test_build_key_filter_conditions_expires_now_is_call_time_utc():
    """The lt(now) boundary is computed at call time as a tz-aware UTC datetime."""
    from datetime import datetime, timezone

    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _build_key_filter_conditions,
    )

    before = datetime.now(timezone.utc)
    where = _build_key_filter_conditions(
        user_id="u1",
        team_id=None,
        organization_id=None,
        key_alias=None,
        key_hash=None,
        exclude_team_id=None,
        admin_team_ids=None,
        expires_filter="expired",
    )
    after = datetime.now(timezone.utc)

    lt_values = [c["lt"] for c in _find_expires_clauses(where) if isinstance(c, dict) and "lt" in c]
    assert len(lt_values) == 1
    now_value = lt_values[0]
    assert now_value.tzinfo is not None
    assert now_value.utcoffset().total_seconds() == 0
    assert before <= now_value <= after


@pytest.mark.asyncio
async def test_list_keys_rejects_invalid_expires():
    """A typo'd expires value must 400, never silently fall back to returning all keys."""
    from unittest.mock import Mock, patch

    mock_prisma_client = AsyncMock()
    mock_user_api_key_dict = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)

    with patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client):
        with pytest.raises(ProxyException) as exc_info:
            await list_keys(
                request=Mock(),
                user_api_key_dict=mock_user_api_key_dict,
                status=None,
                expires="expred",
            )

    assert exc_info.value.code == "400"
    assert "Invalid expires value" in str(exc_info.value.message)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "expires_value, expected_forward",
    [("expired", "expired"), ("active", "active"), (None, None)],
)
async def test_list_keys_forwards_expires_filter(expires_value, expected_forward):
    """list_keys forwards a valid/None expires value verbatim to _list_key_helper as expires_filter."""
    from unittest.mock import Mock, patch

    mock_prisma_client = AsyncMock()
    mock_user_api_key_dict = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    mock_user_info = LiteLLM_UserTable(
        user_id="admin-user",
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )
    mock_helper = AsyncMock(
        return_value={"keys": [], "total_count": 0, "current_page": 1, "total_pages": 0}
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_list_check",
            return_value=mock_user_info,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.list_key_helper",
            mock_helper,
        ),
    ):
        await list_keys(
            request=Mock(),
            user_api_key_dict=mock_user_api_key_dict,
            status=None,
            expires=expires_value,
        )

    mock_helper.assert_called_once()
    assert mock_helper.call_args.kwargs["expires_filter"] == expected_forward


@pytest.mark.asyncio
async def test_list_keys_without_expires_param_forwards_none():
    """Existing callers that never pass `expires` must not 400 and must forward expires_filter=None."""
    from unittest.mock import Mock, patch

    mock_prisma_client = AsyncMock()
    mock_user_api_key_dict = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    mock_user_info = LiteLLM_UserTable(
        user_id="admin-user",
        user_email="[email protected]",
        teams=[],
        organization_memberships=[],
    )
    mock_helper = AsyncMock(
        return_value={"keys": [], "total_count": 0, "current_page": 1, "total_pages": 0}
    )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", mock_prisma_client),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.validate_key_list_check",
            return_value=mock_user_info,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.list_key_helper",
            mock_helper,
        ),
    ):
        await list_keys(
            request=Mock(),
            user_api_key_dict=mock_user_api_key_dict,
            status=None,
        )

    mock_helper.assert_called_once()
    assert mock_helper.call_args.kwargs["expires_filter"] is None


@pytest.mark.asyncio
@patch(
    "litellm.proxy.management_endpoints.key_management_endpoints.rotate_sso_identity_assertions_master_key"
)
@patch(
    "litellm.proxy.management_endpoints.key_management_endpoints.rotate_mcp_user_env_vars_master_key"
)
@patch(
    "litellm.proxy.management_endpoints.key_management_endpoints.rotate_mcp_user_credentials_master_key"
)
@patch(
    "litellm.proxy.management_endpoints.key_management_endpoints.rotate_mcp_server_credentials_master_key"
)
async def test_rotate_master_key_rotates_sso_identity_assertions(
    mock_rotate_mcp_server,
    mock_rotate_mcp_user,
    mock_rotate_env_vars,
    mock_rotate_sso,
):
    """Master-key rotation must re-encrypt the SSO identity assertion store alongside
    the sibling per-user encrypted tables, or a salt rotation orphans every stored
    assertion (step 4d)."""
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        rotate_master_key,
    )

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    mock_tx = AsyncMock()
    mock_tx.litellm_proxymodeltable = MagicMock()
    mock_tx.litellm_proxymodeltable.delete_many = AsyncMock()
    mock_tx.litellm_proxymodeltable.create_many = AsyncMock()
    mock_prisma_client.db.tx = MagicMock(
        return_value=AsyncMock(
            __aenter__=AsyncMock(return_value=mock_tx),
            __aexit__=AsyncMock(return_value=False),
        )
    )
    mock_prisma_client.db.litellm_config.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_credentialstable.find_many = AsyncMock(
        return_value=[]
    )

    mock_proxy_config = MagicMock()
    mock_proxy_config.decrypt_model_list_from_db.return_value = []

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-9876",
        user_id="test-user",
    )

    with patch(
        "litellm.proxy.proxy_server.proxy_config",
        mock_proxy_config,
    ):
        await rotate_master_key(
            prisma_client=mock_prisma_client,
            user_api_key_dict=user_api_key_dict,
            current_master_key="sk-old-master-key",
            new_master_key="sk-new-master-key",
        )

    mock_rotate_sso.assert_awaited_once_with(
        prisma_client=mock_prisma_client,
        new_master_key="sk-new-master-key",
    )


@pytest.mark.asyncio
async def test_rotate_master_key_rotates_search_tools(monkeypatch):
    from types import SimpleNamespace
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.common_utils.encrypt_decrypt_utils import (
        decrypt_if_encrypted_with,
        encrypt_value_helper,
    )
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        rotate_master_key,
    )

    monkeypatch.delenv("LITELLM_SALT_KEY", raising=False)
    monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-old-master-key")

    class _Row(SimpleNamespace):
        def __iter__(self):
            return iter(vars(self).items())

    row = _Row(
        search_tool_id="search-tool-1",
        litellm_params={"search_provider": "tavily", "api_key": encrypt_value_helper("tvly-secret")},
    )

    async def _update_many(where, data):
        expected_litellm_params = json.loads(where["litellm_params"]["equals"])
        if where["search_tool_id"] != row.search_tool_id or expected_litellm_params != row.litellm_params:
            return 0
        row.litellm_params = json.loads(data["litellm_params"])
        return 1

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_config.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_searchtoolstable.find_many = AsyncMock(return_value=[row])
    mock_prisma_client.db.litellm_searchtoolstable.update_many = AsyncMock(side_effect=_update_many)
    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-9876",
        user_id="test-user",
    )

    await rotate_master_key(
        prisma_client=mock_prisma_client,
        user_api_key_dict=user_api_key_dict,
        current_master_key="sk-old-master-key",
        new_master_key="sk-new-master-key",
    )

    assert decrypt_if_encrypted_with(row.litellm_params["api_key"], "sk-new-master-key") == "tvly-secret"
    assert row.litellm_params["search_provider"] == "tavily"


@pytest.mark.asyncio
async def test_check_encryption_endpoint_rejects_proxy_admin_viewer():
    """The residual scan walks and decrypt-classifies every credential-bearing table,
    so it stays proxy_admin-only despite being read-only."""
    from litellm.proxy.management_endpoints import credential_migration as cm
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        check_encryption_endpoint,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
        user_id="viewer-user",
    )
    mock_check = AsyncMock(return_value=cm.MigrationReport())

    with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch.object(
        cm, "check_encryption", mock_check
    ):
        with pytest.raises(HTTPException) as exc_info:
            await check_encryption_endpoint(user_api_key_dict=user_api_key_dict)

    assert exc_info.value.status_code == 403
    mock_check.assert_not_awaited()


@pytest.mark.asyncio
async def test_migrate_encryption_endpoint_rejects_proxy_admin_viewer():
    """The re-encryption write sibling is also proxy_admin-only."""
    from litellm.proxy.management_endpoints import credential_migration as cm
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        migrate_encryption_endpoint,
    )

    user_api_key_dict = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
        user_id="viewer-user",
    )
    mock_migrate = AsyncMock(return_value=cm.MigrationReport())

    with patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), patch.object(
        cm, "migrate_encryption", mock_migrate
    ):
        with pytest.raises(HTTPException) as exc_info:
            await migrate_encryption_endpoint(
                user_api_key_dict=user_api_key_dict, dry_run=False
            )

    assert exc_info.value.status_code == 403
    mock_migrate.assert_not_awaited()


_ESTIMATE = "default_estimated_output_tokens"
_ESTIMATE_PER_MODEL = "default_estimated_output_tokens_per_model"


@pytest.mark.parametrize(
    "label, request_body, existing_metadata, allowed",
    [
        ("nothing declared", {}, None, True),
        ("declared top-level on a key with none stored", {_ESTIMATE: 1}, None, False),
        ("declared inside metadata on a key with none stored", {"metadata": {_ESTIMATE: 1}}, None, False),
        (
            "per-model map declared inside metadata",
            {"metadata": {_ESTIMATE_PER_MODEL: {"gpt-4": 1}}},
            None,
            False,
        ),
        ("unrelated edit, metadata omitted", {"models": ["gpt-4"]}, {_ESTIMATE: 2000}, True),
        ("stored value resent unchanged", {_ESTIMATE: 2000}, {_ESTIMATE: 2000}, True),
        ("stored value lowered", {_ESTIMATE: 1}, {_ESTIMATE: 2000}, False),
        ("stored value raised", {_ESTIMATE: 9000}, {_ESTIMATE: 2000}, False),
        (
            "stored value cleared by sending a metadata blob without it",
            {"metadata": {"other": "keep"}},
            {_ESTIMATE: 2000, "other": "keep"},
            False,
        ),
        (
            "stored value resent inside the metadata blob",
            {"metadata": {_ESTIMATE: 2000, "other": "keep"}},
            {_ESTIMATE: 2000, "other": "keep"},
            True,
        ),
        (
            "per-model map resent unchanged",
            {_ESTIMATE_PER_MODEL: {"gpt-4": 4096}},
            {_ESTIMATE_PER_MODEL: {"gpt-4": 4096}},
            True,
        ),
        (
            "one model in the per-model map lowered",
            {_ESTIMATE_PER_MODEL: {"gpt-4": 1}},
            {_ESTIMATE_PER_MODEL: {"gpt-4": 4096}},
            False,
        ),
    ],
)
def test_output_token_estimate_admin_gate_matrix(label, request_body, existing_metadata, allowed):
    """A non-admin may only leave a key's stored output-token estimate exactly as it is.

    The estimate decides what the TPM limiter reserves for a request that omits
    max_tokens, so lowering, raising or clearing it moves a reservation charged
    against team and organization windows the key holder does not own. Key
    metadata is writable by the key holder, and the declaration can be written
    either as a dedicated top-level field or nested in the metadata blob, so
    both routes are gated. Resending the stored value is what the edit form
    produces on every save and has to stay allowed.
    """
    from litellm.proxy.auth.auth_utils import (
        enforce_output_token_estimates_are_admin_only,
    )

    def _call(caller):
        enforce_output_token_estimates_are_admin_only(
            data=UpdateKeyRequest(key="sk-1", **request_body),
            existing_metadata=existing_metadata,
            user_api_key_dict=caller,
            entity="key",
        )

    non_admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-non-admin",
        user_id="alice",
    )
    if allowed:
        _call(non_admin)
    else:
        with pytest.raises(HTTPException) as exc:
            _call(non_admin)
        assert exc.value.status_code == 403
        assert "Only proxy admins can set" in str(exc.value.detail)

    _call(
        UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin",
        )
    )


@pytest.mark.asyncio
async def test_generate_key_output_token_estimate_rejected_for_non_admin():
    """The /key/update gate does not cover generate, so without its own check a
    non-admin could self-mint a key that reserves one output token per
    unbounded request and overrun the TPM window it is charged against."""
    with patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()):
        with pytest.raises(HTTPException) as exc:
            await _common_key_generation_helper(
                data=GenerateKeyRequest(default_estimated_output_tokens=1, tpm_limit=100000),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.INTERNAL_USER,
                    api_key="sk-alice",
                    user_id="alice",
                ),
                litellm_changed_by=None,
                team_table=None,
            )
    assert int(getattr(exc.value, "status_code", 0)) == 403
    assert "Only proxy admins can set" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_generate_key_output_token_estimate_in_metadata_rejected_for_non_admin():
    """Writing the declaration into the raw metadata blob lands in the same
    stored field, so gating only the dedicated top-level field leaves the
    bypass wide open."""
    with patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()):
        with pytest.raises(HTTPException) as exc:
            await _common_key_generation_helper(
                data=GenerateKeyRequest(metadata={"default_estimated_output_tokens": 1}),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.INTERNAL_USER,
                    api_key="sk-alice",
                    user_id="alice",
                ),
                litellm_changed_by=None,
                team_table=None,
            )
    assert int(getattr(exc.value, "status_code", 0)) == 403


@pytest.mark.asyncio
async def test_generate_key_output_token_estimate_allowed_for_admin():
    """A proxy admin declaring the estimate must reach key creation."""
    with (
        patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"
        ) as mock_generate_key,
    ):
        mock_generate_key.return_value = {
            "key": "sk-test-key",
            "expires": None,
            "user_id": "admin",
            "team_id": None,
        }
        await _common_key_generation_helper(
            data=GenerateKeyRequest(default_estimated_output_tokens=200),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
            litellm_changed_by=None,
            team_table=None,
        )
    assert mock_generate_key.called


def _estimate_key_row(token: str, metadata: dict):
    existing_key = MagicMock()
    existing_key.token = token
    existing_key.user_id = "internal_user"
    existing_key.created_by = "internal_user"
    existing_key.team_id = None
    existing_key.project_id = None
    existing_key.max_budget = 10.0
    existing_key.key_alias = None
    existing_key.models = []
    existing_key.metadata = metadata
    existing_key.model_dump.return_value = {
        "token": token,
        "user_id": "internal_user",
        "team_id": None,
        "max_budget": 10.0,
    }
    return existing_key


def _wire_update_key_fn(
    monkeypatch: pytest.MonkeyPatch, existing_key: LiteLLM_VerificationToken | MagicMock
) -> AsyncMock:
    mock_prisma_client = AsyncMock()
    updated_key = MagicMock()
    updated_key.token = existing_key.token
    updated_key.key_alias = "my-alias"

    mock_prisma_client.get_data = AsyncMock(return_value=existing_key)
    mock_prisma_client.update_data = AsyncMock(return_value=updated_key)
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing_key)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", AsyncMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)
    monkeypatch.setattr("litellm.proxy.proxy_server.hash_token", lambda token: existing_key.token)

    async def _noop(**kwargs):
        pass

    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        _noop,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints._enforce_unique_key_alias",
        _noop,
    )
    return mock_prisma_client


@pytest.mark.asyncio
async def test_update_key_output_token_estimate_lowered_rejected_for_non_admin(monkeypatch):
    """End-to-end wiring: a key's owner reaches /key/update without any admin
    check because metadata is a non-budget field, so the gate has to fire
    inside the update path itself rather than only in a helper."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    token = "a1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_ESTIMATE: 4000}))

    mock_request = MagicMock()
    mock_request.query_params = {}

    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key=token, default_estimated_output_tokens=1),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-internal",
                user_id="internal_user",
            ),
            litellm_changed_by=None,
        )

    assert str(exc.value.code) == "403"
    assert "Only proxy admins can set" in str(exc.value.message)


@pytest.mark.asyncio
async def test_update_key_output_token_estimate_unchanged_allows_non_admin_edit(monkeypatch):
    """The edit form resends every field it renders, so gating on presence
    would 403 a key owner renaming their own key."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    token = "b1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_ESTIMATE: 4000}))

    mock_request = MagicMock()
    mock_request.query_params = {}

    result = await update_key_fn(
        request=mock_request,
        data=UpdateKeyRequest(key=token, key_alias="my-alias", default_estimated_output_tokens=4000),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-internal",
            user_id="internal_user",
        ),
        litellm_changed_by=None,
    )

    assert result is not None


@pytest.mark.asyncio
async def test_regenerate_key_output_token_estimate_lowered_rejected_for_non_admin():
    """/key/regenerate is a third write path into the same stored metadata.

    can_modify_verification_token lets a key's own holder regenerate it, and
    the request body runs through prepare_key_update_data exactly as an update
    does, so gating only generate and update leaves the declaration writable.
    """
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    token = "c1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    key_in_db = LiteLLM_VerificationToken(
        token=token,
        user_id="internal_user",
        metadata={_ESTIMATE: 4000},
    )

    with pytest.raises(HTTPException) as exc:
        await _execute_virtual_key_regeneration(
            prisma_client=AsyncMock(),
            key_in_db=key_in_db,
            hashed_api_key=token,
            key="sk-original",
            data=RegenerateKeyRequest(key="sk-original", default_estimated_output_tokens=1),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-internal",
                user_id="internal_user",
            ),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert exc.value.status_code == 403
    assert "Only proxy admins can set" in str(exc.value.detail)


_BATCH_LIMIT = "batch_enqueued_token_limit"


_UNTOUCHED = object()


@pytest.mark.parametrize(
    "limit_key",
    [
        "batch_enqueued_token_limit",
        "max_batch_file_records",
        "max_batch_file_uploads_per_day",
        "max_file_downloads_per_minute",
    ],
)
@pytest.mark.parametrize(
    "label, sent, stored, allowed",
    [
        ("set on a key with none stored", 50000, None, False),
        ("raised above the stored limit", 200000, 100000, False),
        ("cleared by replacing the blob", None, 100000, False),
        ("resent unchanged", 100000, 100000, True),
        ("left untouched", _UNTOUCHED, 100000, True),
    ],
)
def test_batch_limits_admin_gate_matrix(limit_key, label, sent, stored, allowed):
    request_body = {} if sent is _UNTOUCHED else {"metadata": {} if sent is None else {limit_key: sent}}
    existing_metadata = None if stored is None else {limit_key: stored}
    from litellm.proxy.auth.auth_utils import (
        enforce_batch_limits_are_admin_only,
    )

    def _call(caller):
        enforce_batch_limits_are_admin_only(
            data=UpdateKeyRequest(key="sk-1", **request_body),
            existing_metadata=existing_metadata,
            user_api_key_dict=caller,
            entity="key",
        )

    non_admin = UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-non-admin",
        user_id="alice",
    )
    if allowed:
        _call(non_admin)
    else:
        with pytest.raises(HTTPException) as exc:
            _call(non_admin)
        assert exc.value.status_code == 403
        assert f"Only proxy admins can set {limit_key}" in str(exc.value.detail)

    _call(
        UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin",
        )
    )


@pytest.mark.asyncio
async def test_generate_key_batch_enqueued_token_limit_rejected_for_non_admin():
    """A non-admin self-minting a key with the limit would replace the standard
    batch RPM/TPM checks with a cap of their own choosing."""
    with patch("litellm.proxy.proxy_server.prisma_client", AsyncMock()):
        with pytest.raises(HTTPException) as exc:
            await _common_key_generation_helper(
                data=GenerateKeyRequest(metadata={_BATCH_LIMIT: 100000}, rpm_limit=2),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.INTERNAL_USER,
                    api_key="sk-alice",
                    user_id="alice",
                ),
                litellm_changed_by=None,
                team_table=None,
            )
    assert int(getattr(exc.value, "status_code", 0)) == 403
    assert "Only proxy admins can set" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_update_key_batch_enqueued_token_limit_raised_rejected_for_non_admin(monkeypatch):
    """/key/update is reachable by the key's own holder, so the gate has to
    fire inside the update path itself rather than only at generation."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    token = "d1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_BATCH_LIMIT: 100000}))

    mock_request = MagicMock()
    mock_request.query_params = {}

    with pytest.raises(ProxyException) as exc:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(key=token, metadata={_BATCH_LIMIT: 10**12}),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-internal",
                user_id="internal_user",
            ),
            litellm_changed_by=None,
        )

    assert str(exc.value.code) == "403"
    assert "Only proxy admins can set" in str(exc.value.message)


@pytest.mark.asyncio
async def test_update_key_batch_enqueued_token_limit_unchanged_allows_non_admin_edit(monkeypatch):
    """The edit form resends every field it renders, so gating on presence
    would 403 a key owner renaming a key that carries an admin-set limit."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    token = "e1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    _wire_update_key_fn(monkeypatch, _estimate_key_row(token, {_BATCH_LIMIT: 100000}))

    mock_request = MagicMock()
    mock_request.query_params = {}

    result = await update_key_fn(
        request=mock_request,
        data=UpdateKeyRequest(key=token, key_alias="my-alias", metadata={_BATCH_LIMIT: 100000}),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-internal",
            user_id="internal_user",
        ),
        litellm_changed_by=None,
    )

    assert result is not None


@pytest.mark.asyncio
async def test_regenerate_key_batch_enqueued_token_limit_rejected_for_non_admin():
    """/key/regenerate runs the request body through prepare_key_update_data
    exactly as an update does, so it is a third write path into the field."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    token = "f1b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    key_in_db = LiteLLM_VerificationToken(
        token=token,
        user_id="internal_user",
        metadata={_BATCH_LIMIT: 100000},
    )

    with pytest.raises(HTTPException) as exc:
        await _execute_virtual_key_regeneration(
            prisma_client=AsyncMock(),
            key_in_db=key_in_db,
            hashed_api_key=token,
            key="sk-original",
            data=RegenerateKeyRequest(key="sk-original", metadata={_BATCH_LIMIT: 10**12}),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-internal",
                user_id="internal_user",
            ),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert exc.value.status_code == 403
    assert "Only proxy admins can set" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_bulk_key_update_batch_enqueued_token_limit_rejected_for_non_admin():
    """Bulk team-key updates run through _process_single_key_update, not
    /key/update's validator, so the gate must also live on that path."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _process_single_key_update,
    )

    token = "a2b2c3d4e5f6789012345678901234567890123456789012345678901234abcd"
    existing = _estimate_key_row(token, {_BATCH_LIMIT: 100000})

    with pytest.raises(HTTPException) as exc:
        await _process_single_key_update(
            update_key_request=UpdateKeyRequest(key=token, metadata={_BATCH_LIMIT: 10**12}),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-internal",
                user_id="internal_user",
            ),
            litellm_changed_by=None,
            prisma_client=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=None,
            existing_key_row=existing,
        )

    assert exc.value.status_code == 403
    assert "Only proxy admins can set" in str(exc.value.detail)


@pytest.mark.asyncio
async def test_execute_virtual_key_regeneration_stamps_settings_updated_at():
    """Regenerate rewrites the key's config, so it must move settings_updated_at."""
    from datetime import datetime, timezone

    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    mock_prisma_client = _make_regenerate_mock_prisma()

    with _patch_regenerate_side_effects():
        before = datetime.now(timezone.utc)
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=_make_regenerate_existing_key(),
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(max_budget=42.0),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )
        after = datetime.now(timezone.utc)

    sent = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs["data"]
    assert sent["max_budget"] == 42.0
    assert before <= sent["settings_updated_at"] <= after


@pytest.mark.asyncio
async def test_block_key_stamps_settings_updated_at(monkeypatch):
    """Blocking a key is a config change, not spend activity."""
    from datetime import datetime, timezone

    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import block_key

    mock_prisma_client, _ = _setup_block_unblock_mocks(monkeypatch)

    before = datetime.now(timezone.utc)
    await block_key(
        data=BlockKeyRequest(key="sk-test123456789"),
        http_request=MagicMock(),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin_user",
        ),
        litellm_changed_by=None,
    )
    after = datetime.now(timezone.utc)

    sent = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs["data"]
    assert sent["blocked"] is True
    assert before <= sent["settings_updated_at"] <= after


@pytest.mark.asyncio
async def test_unblock_key_stamps_settings_updated_at(monkeypatch):
    """Unblocking a key is a config change, not spend activity."""
    from datetime import datetime, timezone

    from litellm.proxy._types import BlockKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import unblock_key

    mock_prisma_client, _ = _setup_block_unblock_mocks(monkeypatch)

    before = datetime.now(timezone.utc)
    await unblock_key(
        data=BlockKeyRequest(key="sk-test123456789"),
        http_request=MagicMock(),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-admin",
            user_id="admin_user",
        ),
        litellm_changed_by=None,
    )
    after = datetime.now(timezone.utc)

    sent = mock_prisma_client.db.litellm_verificationtoken.update.call_args.kwargs["data"]
    assert sent["blocked"] is False
    assert before <= sent["settings_updated_at"] <= after


def _wire_key_generation_prisma(monkeypatch):
    created_key = MagicMock(token="hashed_token_123", litellm_budget_table=None, object_permission=None)

    mock_prisma_client = AsyncMock()
    mock_prisma_client.insert_data = AsyncMock(return_value=created_key)
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(return_value=created_key)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    return mock_prisma_client.insert_data


async def _generate_key_and_get_persisted_row(data: GenerateKeyRequest, mock_insert_data):
    await _common_key_generation_helper(
        data=data,
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-9876",
            user_id="1234",
        ),
        litellm_changed_by=None,
        team_table=None,
    )
    key_call = next(c for c in mock_insert_data.call_args_list if c.kwargs["table_name"] == "key")
    return key_call.kwargs["data"]


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_fills_unset(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    response: Final = await generate_key_fn(
        data=GenerateKeyRequest(),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-internal",
            user_id="internal-user",
        ),
        litellm_changed_by=None,
    )

    assert response is not None
    key_call: Final = next(c for c in mock_insert_data.call_args_list if c.kwargs["table_name"] == "key")
    assert key_call.kwargs["data"]["allowed_routes"] == ["llm_api_routes", "/key/spend/report"]


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_keeps_explicit_value(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(
        GenerateKeyRequest(allowed_routes=["info_routes"]),
        mock_insert_data,
    )

    assert key_row["allowed_routes"] == ["info_routes"]


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_extends_key_type_preset_it_covers(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy._types import LiteLLMKeyType

    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    await generate_key_fn(
        data=GenerateKeyRequest(key_type=LiteLLMKeyType.LLM_API),
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.INTERNAL_USER,
            api_key="sk-internal",
            user_id="internal-user",
        ),
        litellm_changed_by=None,
    )

    key_call: Final = next(c for c in mock_insert_data.call_args_list if c.kwargs["table_name"] == "key")
    assert key_call.kwargs["data"]["allowed_routes"] == ["llm_api_routes", "/key/spend/report"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("key_type", "preset_routes"),
    [(LiteLLMKeyType.MANAGEMENT, ["management_routes"]), (LiteLLMKeyType.READ_ONLY, ["info_routes"])],
)
async def test_default_key_generate_params_allowed_routes_keeps_management_and_read_only_presets(
    monkeypatch: pytest.MonkeyPatch, key_type: LiteLLMKeyType, preset_routes: list[str]
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "management_routes", "info_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(
        GenerateKeyRequest(key_type=key_type),
        mock_insert_data,
    )

    assert key_row["allowed_routes"] == preset_routes


@pytest.mark.parametrize(
    "data",
    [GenerateKeyRequest(), GenerateKeyRequest(key_type=LiteLLMKeyType.LLM_API)],
    ids=["unset", "llm_api"],
)
def test_effective_key_for_generate_shows_default_allowed_routes_to_the_policy(
    monkeypatch: pytest.MonkeyPatch, data: GenerateKeyRequest
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )

    effective_key: Final = _effective_key_for_generate(data=data, now=datetime(2026, 1, 1, tzinfo=timezone.utc))

    assert effective_key.allowed_routes == ["llm_api_routes", "/key/spend/report"]


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_skips_team_service_account_keys(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(
        GenerateKeyRequest(team_id="team-a", metadata={"service_account_id": "sa-1"}),
        mock_insert_data,
    )

    assert not key_row.get("allowed_routes")


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_skips_full_access_keys(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(
        GenerateKeyRequest(key_type=LiteLLMKeyType.DEFAULT),
        mock_insert_data,
    )

    assert not key_row.get("allowed_routes")


def _owner_route_update_status(existing: list[str], incoming: list[str]) -> int | None:
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _enforce_allowed_routes_update_permission,
    )

    try:
        _enforce_allowed_routes_update_permission(
            data=UpdateKeyRequest(key="sk-owned", allowed_routes=incoming),
            existing_key_row=LiteLLM_VerificationToken(
                token="hashed-owned", user_id="internal-user", allowed_routes=existing
            ),
            user_api_key_dict=UserAPIKeyAuth(user_id="internal-user", user_role=LitellmUserRoles.INTERNAL_USER),
        )
    except HTTPException as exc:
        return exc.status_code
    return None


@pytest.mark.parametrize(
    ("existing", "incoming", "expected_status"),
    [
        (["llm_api_routes"], [], None),
        (["llm_api_routes", "/key/spend/report"], [], 403),
        (["llm_api_routes", "/key/spend/report"], ["llm_api_routes"], 403),
        (["llm_api_routes", "/key/spend/report"], ["llm_api_routes", "/key/spend/report"], None),
        (["llm_api_routes", "/key/spend/report"], ["/key/spend/report", "llm_api_routes"], 403),
        (
            ["llm_api_routes", "/key/spend/report"],
            ["llm_api_routes", "/key/spend/report", "/key/spend/report"],
            403,
        ),
        (["/global/spend/report"], ["/global/spend/report"], None),
    ],
    ids=[
        "preset_to_full_access",
        "default_list_to_full_access",
        "default_list_to_ai_apis",
        "default_list_sent_back_unchanged",
        "default_list_sent_back_reordered",
        "default_list_sent_back_with_a_duplicate",
        "admin_set_list_sent_back_unchanged",
    ],
)
def test_owner_cannot_change_the_routes_a_key_got_from_default_key_generate_params(
    monkeypatch: pytest.MonkeyPatch, existing: list[str], incoming: list[str], expected_status: int | None
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )

    assert _owner_route_update_status(existing, incoming) == expected_status


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("incoming", "written"),
    [
        (["llm_api_routes", "/key/spend/report"], None),
        (["/key/spend/report", "llm_api_routes"], ["/key/spend/report", "llm_api_routes"]),
        (["llm_api_routes"], ["llm_api_routes"]),
    ],
    ids=["unchanged_resend", "reordered", "changed"],
)
async def test_key_update_writes_allowed_routes_only_when_they_change(
    incoming: list[str], written: list[str] | None
) -> None:
    existing_key: Final = LiteLLM_VerificationToken(
        token="hashed", allowed_routes=["llm_api_routes", "/key/spend/report"]
    )

    update_values: Final = await prepare_key_update_data(
        data=UpdateKeyRequest(key="sk-1", key_alias="renamed", allowed_routes=incoming), existing_key_row=existing_key
    )

    assert (update_values["key_alias"], update_values.get("allowed_routes")) == ("renamed", written)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("request_data", "expected_routes"),
    [(GenerateKeyRequest(), []), (GenerateKeyRequest(key_type=LiteLLMKeyType.LLM_API), ["llm_api_routes"])],
    ids=["no_key_type", "ai_apis"],
)
async def test_default_key_generate_params_allowed_routes_with_a_non_string_entry_is_ignored(
    monkeypatch: pytest.MonkeyPatch, request_data: GenerateKeyRequest, expected_routes: list[str]
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", 123]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(request_data, mock_insert_data)

    assert (key_row.get("allowed_routes") or []) == expected_routes


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_empty_list_treated_as_unset(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(
        litellm,
        "default_key_generate_params",
        {"allowed_routes": ["llm_api_routes", "/key/spend/report"]},
    )
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(
        GenerateKeyRequest(allowed_routes=[]),
        mock_insert_data,
    )

    assert key_row["allowed_routes"] == ["llm_api_routes", "/key/spend/report"]


@pytest.mark.asyncio
async def test_default_key_generate_params_allowed_routes_ignores_a_string_value(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(litellm, "default_key_generate_params", {"allowed_routes": "llm_api_routes"})
    mock_insert_data: Final = _wire_key_generation_prisma(monkeypatch)

    key_row: Final = await _generate_key_and_get_persisted_row(GenerateKeyRequest(), mock_insert_data)

    assert not key_row.get("allowed_routes")


@pytest.mark.asyncio
async def test_key_generate_explicit_null_budget_duration_beats_default_key_generate_params(monkeypatch):
    """An explicit `"budget_duration": null` asks for a budget that never resets.

    Gating on the value alone made that indistinguishable from omitting the field,
    so the configured default overrode the opt-out and budget_reset_at got stamped.
    """
    monkeypatch.setattr(litellm, "default_key_generate_params", {"budget_duration": "30d"})
    mock_insert_data = _wire_key_generation_prisma(monkeypatch)

    key_row = await _generate_key_and_get_persisted_row(GenerateKeyRequest(budget_duration=None), mock_insert_data)

    assert key_row["budget_duration"] is None
    assert key_row["budget_reset_at"] is None


@pytest.mark.asyncio
async def test_key_generate_omitted_budget_duration_still_takes_default_key_generate_params(monkeypatch):
    """Omitting the field keeps applying the default, the behavior the explicit-null fix must not break."""
    monkeypatch.setattr(litellm, "default_key_generate_params", {"budget_duration": "30d"})
    mock_insert_data = _wire_key_generation_prisma(monkeypatch)

    key_row = await _generate_key_and_get_persisted_row(GenerateKeyRequest(), mock_insert_data)

    assert key_row["budget_duration"] == "30d"
    assert key_row["budget_reset_at"] is not None


@pytest.mark.asyncio
async def test_key_generate_explicit_null_budget_duration_cannot_bypass_upperbound(monkeypatch):
    """upperbound_key_generate_params is an admin ceiling: an explicit null must not mint an uncapped key,
    otherwise any key creator could bypass configured limits (duration, budgets, rate limits)."""
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(litellm, "default_key_generate_params", None)
    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(budget_duration="30d"),
    )
    mock_insert_data = _wire_key_generation_prisma(monkeypatch)

    key_row = await _generate_key_and_get_persisted_row(GenerateKeyRequest(budget_duration=None), mock_insert_data)

    assert key_row["budget_duration"] == "30d"
    assert key_row["budget_reset_at"] is not None


@pytest.mark.asyncio
async def test_key_generate_omitted_budget_duration_still_filled_by_upperbound(monkeypatch):
    """The upperbound's long-standing fill-on-omitted behavior stays untouched."""
    from litellm.types.proxy.management_endpoints.ui_sso import (
        LiteLLM_UpperboundKeyGenerateParams,
    )

    monkeypatch.setattr(litellm, "default_key_generate_params", None)
    monkeypatch.setattr(
        litellm,
        "upperbound_key_generate_params",
        LiteLLM_UpperboundKeyGenerateParams(budget_duration="30d"),
    )
    mock_insert_data = _wire_key_generation_prisma(monkeypatch)

    key_row = await _generate_key_and_get_persisted_row(GenerateKeyRequest(), mock_insert_data)

    assert key_row["budget_duration"] == "30d"
    assert key_row["budget_reset_at"] is not None
from litellm.proxy.management_helpers.access_group_key_sync import (
    _ATTACH_KEY_SQL,
    _DETACH_KEY_SQL,
    _REPOINT_KEY_SQL,
)

ACCESS_GROUP_SYNC_TOKEN = "0d62f396c1317066f55a96086517047c737087c61eb2bf016b72e6298927b15b"


def _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups):
    """
    Back the access group table with an in-memory dict so the sync's writes are observable.

    The sync writes through guarded set-based SQL statements, so this emulates exactly what
    Postgres does with them, including the guards that make each one idempotent and the
    `RETURNING` clause that reports which groups actually moved.
    """

    def _repoint(previous_token, new_token):
        moved = [
            group_id
            for group_id, stored in access_groups.items()
            if previous_token in stored["assigned_key_ids"]
        ]
        for group_id in moved:
            current = access_groups[group_id]["assigned_key_ids"]
            access_groups[group_id]["assigned_key_ids"] = [
                *(t for t in current if t not in (previous_token, new_token)),
                new_token,
            ]
        return moved

    def _attach(key_token, access_group_ids):
        moved = [
            group_id
            for group_id in access_group_ids
            if group_id in access_groups
            and key_token not in access_groups[group_id]["assigned_key_ids"]
        ]
        for group_id in moved:
            stored = access_groups[group_id]
            stored["assigned_key_ids"] = [*stored["assigned_key_ids"], key_token]
        return moved

    def _detach(key_token, access_group_ids):
        moved = [
            group_id
            for group_id in access_group_ids
            if group_id in access_groups
            and key_token in access_groups[group_id]["assigned_key_ids"]
        ]
        for group_id in moved:
            stored = access_groups[group_id]
            stored["assigned_key_ids"] = [
                t for t in stored["assigned_key_ids"] if t != key_token
            ]
        return moved

    async def _query_raw(query, *args):
        if query == _REPOINT_KEY_SQL:
            moved = _repoint(*args)
        elif query == _ATTACH_KEY_SQL:
            moved = _attach(*args)
        else:
            assert query == _DETACH_KEY_SQL, f"unexpected statement: {query}"
            moved = _detach(*args)
        return [{"access_group_id": group_id} for group_id in moved]

    raw_mock = AsyncMock(side_effect=_query_raw)
    mock_prisma_client.db.query_raw = raw_mock
    return raw_mock


async def _authorized_models_for_key(access_groups, token, key_access_group_ids):
    """Run the real auth-time reader against the post-sync access group rows."""
    from litellm.proxy._types import LiteLLM_AccessGroupTable, LiteLLM_TeamTable
    from litellm.proxy.auth.auth_checks import (
        get_authorized_resources_from_key_access_groups,
    )

    async def _get_access_object(*, access_group_id, **_kwargs):
        stored = access_groups[access_group_id]
        return LiteLLM_AccessGroupTable(
            access_group_id=access_group_id,
            access_group_name=access_group_id,
            access_model_names=list(stored["access_model_names"]),
            assigned_team_ids=[],
            assigned_key_ids=list(stored["assigned_key_ids"]),
        )

    with (
        patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
        patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
        patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
        patch(
            "litellm.proxy.auth.auth_checks.get_access_object",
            new_callable=AsyncMock,
            side_effect=_get_access_object,
        ),
    ):
        return await get_authorized_resources_from_key_access_groups(
            valid_token=UserAPIKeyAuth(
                token=token,
                models=[],
                team_id="team-a",
                access_group_ids=list(key_access_group_ids),
            ),
            team_object=LiteLLM_TeamTable(team_id="team-a", models=[]),
            resource_field="access_model_names",
        )


@pytest.mark.asyncio
async def test_update_key_syncs_access_group_assigned_key_ids_in_both_directions(
    monkeypatch,
):
    """
    A key-side edit of `access_group_ids` must be mirrored onto every affected access
    group's `assigned_key_ids`, in one operation, in both directions.

    `assigned_key_ids` is not display-only. `get_authorized_resources_from_key_access_groups`
    reads it as an authorization input and authorizes only when the group lists the key's
    token, so a group the key just added must start granting its resources and a group the
    key dropped must stop. A single-direction assertion would pass against a fix that only
    ever adds (or only ever removes), so this covers add, remove, untouched, and the
    authorization consequence of each.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=["ag-drop", "ag-keep"],
    )
    access_groups = {
        "ag-drop": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
            "access_model_names": ["dropped-model"],
        },
        "ag-keep": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
            "access_model_names": ["kept-model"],
        },
        "ag-add": {"assigned_key_ids": [], "access_model_names": ["added-model"]},
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {}})
    raw_mock = _access_group_table_mocks(
        monkeypatch, mock_prisma_client, access_groups
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ) as invalidate_cache,
    ):
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(
                key=ACCESS_GROUP_SYNC_TOKEN, access_group_ids=["ag-keep", "ag-add"]
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
        )

    assert access_groups["ag-drop"]["assigned_key_ids"] == []
    assert access_groups["ag-add"]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]
    assert access_groups["ag-keep"]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]

    # Both halves go out as single guarded statements. A read-modify-write here lets two
    # admins editing one group lose each other's change: an attach can vanish, and a detach
    # can put an already revoked token back and restore its grants.
    assert sorted(call.args for call in raw_mock.call_args_list) == sorted(
        [
            (_ATTACH_KEY_SQL, ACCESS_GROUP_SYNC_TOKEN, ["ag-add"]),
            (_DETACH_KEY_SQL, ACCESS_GROUP_SYNC_TOKEN, ["ag-drop"]),
        ]
    )
    assert {call.args[0] for call in invalidate_cache.call_args_list} == {
        "ag-drop",
        "ag-add",
    }

    authorized_models = await _authorized_models_for_key(
        access_groups,
        ACCESS_GROUP_SYNC_TOKEN,
        ["ag-drop", "ag-keep", "ag-add"],
    )
    assert sorted(authorized_models) == ["added-model", "kept-model"]


@pytest.mark.asyncio
async def test_update_key_leaves_access_groups_alone_when_field_is_unset(monkeypatch):
    """
    An update that never mentions `access_group_ids` must not touch the group rows.

    `prepare_key_update_data` writes from `model_dump(exclude_unset=True)`, so an omitted
    field leaves the key row's own list intact. Reading the request attribute instead of
    its `model_fields_set` would see None and wipe every group's copy of the token on any
    unrelated edit, e.g. a max_budget change.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=["ag-keep"],
    )
    access_groups = {
        "ag-keep": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
            "access_model_names": ["kept-model"],
        },
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {}})
    raw_mock = _access_group_table_mocks(
        monkeypatch, mock_prisma_client, access_groups
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
        new_callable=AsyncMock,
    ):
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key=ACCESS_GROUP_SYNC_TOKEN, max_budget=50.0),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
        )

    raw_mock.assert_not_called()
    assert access_groups["ag-keep"]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]
    assert await _authorized_models_for_key(
        access_groups, ACCESS_GROUP_SYNC_TOKEN, ["ag-keep"]
    ) == ["kept-model"]


@pytest.mark.asyncio
async def test_bulk_update_keys_syncs_access_group_assigned_key_ids(monkeypatch):
    """
    /key/bulk_update and /team/keys/bulk_update reach the DB through
    `_process_single_key_update`, which is a separate write path from /key/update's own
    inline one. Both have to maintain the group's copy or a bulk attach grants nothing.
    """
    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=["ag-drop"],
    )
    access_groups = {
        "ag-drop": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
            "access_model_names": ["dropped-model"],
        },
        "ag-add": {"assigned_key_ids": [], "access_model_names": ["added-model"]},
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {}})
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint",
            new_callable=AsyncMock,
        ),
    ):
        await _process_single_key_update(
            update_key_request=UpdateKeyRequest(
                key=ACCESS_GROUP_SYNC_TOKEN, access_group_ids=["ag-add"]
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
            prisma_client=mock_prisma_client,
            user_api_key_cache=AsyncMock(),
            proxy_logging_obj=MagicMock(),
            llm_router=None,
            existing_key_row=key_in_db,
        )

    assert access_groups["ag-drop"]["assigned_key_ids"] == []
    assert access_groups["ag-add"]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]
    assert await _authorized_models_for_key(
        access_groups, ACCESS_GROUP_SYNC_TOKEN, ["ag-drop", "ag-add"]
    ) == ["added-model"]


@pytest.mark.asyncio
async def test_delete_key_withdraws_token_from_its_access_groups(monkeypatch):
    """
    Deleting a key must withdraw its token from every group that lists it.

    Without the withdrawal the group keeps a token that no longer resolves to a row, so
    the access group page lists a key that does not exist and the list grows without bound.
    """
    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=["ag-keep"],
    )
    access_groups = {
        "ag-keep": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN, "other-key"],
            "access_model_names": ["kept-model"],
        },
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(
        return_value=[key_in_db]
    )
    mock_prisma_client.delete_data = AsyncMock(return_value={"deleted_keys": 1})
    mock_prisma_client.db.litellm_deletedverificationtoken.create_many = AsyncMock()
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
    )

    mock_cache = MagicMock()
    mock_cache.delete_cache = MagicMock()

    with patch(
        "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
        new_callable=AsyncMock,
    ):
        await delete_verification_tokens(
            tokens=[ACCESS_GROUP_SYNC_TOKEN],
            user_api_key_cache=mock_cache,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by="admin-user",
        )

    assert access_groups["ag-keep"]["assigned_key_ids"] == ["other-key"]


@pytest.mark.asyncio
async def test_generate_key_records_token_in_its_access_groups(monkeypatch):
    """
    /key/generate with `access_group_ids` must record the new token on the group side.

    The key row's own list alone does not authorize: the group has to list the token back
    or `get_authorized_resources_from_key_access_groups` contributes nothing, so a key
    created against a group silently gets none of its models.
    """
    access_groups = {
        "ag-add": {"assigned_key_ids": [], "access_model_names": ["added-model"]},
    }

    created_key = MagicMock()
    created_key.token = ACCESS_GROUP_SYNC_TOKEN
    created_key.litellm_budget_table = None
    created_key.created_at = None
    created_key.updated_at = None

    mock_prisma_client = AsyncMock()
    mock_prisma_client.insert_data = AsyncMock(return_value=created_key)
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client", mock_prisma_client
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    monkeypatch.setattr("litellm.store_audit_logs", False)

    with patch(
        "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
        new_callable=AsyncMock,
    ):
        await generate_key_helper_fn(
            request_type="key",
            access_group_ids=["ag-add"],
            table_name="key",
            user_id="test-user",
        )

    assert access_groups["ag-add"]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]
    assert await _authorized_models_for_key(
        access_groups, ACCESS_GROUP_SYNC_TOKEN, ["ag-add"]
    ) == ["added-model"]


@pytest.mark.asyncio
async def test_regenerate_key_repoints_access_group_assigned_key_ids(monkeypatch):
    """
    Regeneration replaces the key's token, which is the identity `assigned_key_ids` stores.

    Leaving the old hash behind points the group at a token that no longer exists AND
    denies the regenerated key the group's grants, so the group's copy has to be
    re-pointed from the old hash to the new one in the same operation.
    """
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    from litellm.proxy.utils import hash_token

    new_token_hash = hash_token("sk-newtoken1234ab12")
    existing_key = LiteLLM_VerificationToken(
        token="abc123",
        user_id="user-1",
        models=["gpt-4"],
        access_group_ids=["ag-keep"],
    )
    access_groups = {
        "ag-keep": {
            "assigned_key_ids": ["abc123"],
            "access_model_names": ["kept-model"],
        },
    }

    mock_prisma_client = _make_regenerate_mock_prisma()
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert access_groups["ag-keep"]["assigned_key_ids"] == [new_token_hash]
    assert await _authorized_models_for_key(
        access_groups, new_token_hash, ["ag-keep"]
    ) == ["kept-model"]
    assert (
        await _authorized_models_for_key(access_groups, "abc123", ["ag-keep"]) == []
    )


@pytest.mark.asyncio
async def test_key_write_paths_revoke_the_key_cache_before_syncing_access_groups(
    monkeypatch,
):
    """
    Credential invalidation must not sit behind the group sync on any key write path.

    The cached auth object still carries the key's old `access_group_ids`, so if the sync
    raises first, the request fails with the key still authenticating against groups it
    just lost, until that entry expires. Ordering it last means a failed sync degrades to
    the stale listing this PR fixes rather than to a stale grant.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    order = []

    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=["ag-drop"],
    )
    access_groups = {
        "ag-drop": {
            "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
            "access_model_names": ["dropped-model"],
        },
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {}})
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)
    mock_prisma_client.db.query_raw = AsyncMock(
        side_effect=lambda *a, **k: order.append("sync") or []
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
            side_effect=lambda **kwargs: order.append("revoke_key_cache"),
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ),
    ):
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(key=ACCESS_GROUP_SYNC_TOKEN, access_group_ids=[]),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
        )

    assert order == ["revoke_key_cache", "sync"]


@pytest.mark.asyncio
async def test_update_key_syncs_many_access_groups_in_one_statement_per_direction(
    monkeypatch,
):
    """
    The number of groups on a request must not become a matching number of round trips.

    Anyone allowed to assign access groups picks the size of `access_group_ids`, so a
    per-group statement lets one /key/update hold a connection for hundreds of sequential
    writes. Both halves are set-based, so the cost is two statements no matter the size.
    """
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        update_key_fn,
    )

    dropped = [f"ag-drop-{i}" for i in range(60)]
    added = [f"ag-add-{i}" for i in range(60)]
    key_in_db = LiteLLM_VerificationToken(
        token=ACCESS_GROUP_SYNC_TOKEN,
        user_id="test-user",
        access_group_ids=dropped,
    )
    access_groups = {
        **{
            group_id: {
                "assigned_key_ids": [ACCESS_GROUP_SYNC_TOKEN],
                "access_model_names": [f"{group_id}-model"],
            }
            for group_id in dropped
        },
        **{
            group_id: {"assigned_key_ids": [], "access_model_names": [f"{group_id}-model"]}
            for group_id in added
        },
    }

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=key_in_db
    )
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=None
    )
    mock_prisma_client.update_data = AsyncMock(return_value={"data": {}})
    raw_mock = _access_group_table_mocks(
        monkeypatch, mock_prisma_client, access_groups
    )
    _setup_update_key_mocks(monkeypatch, mock_prisma_client)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ),
    ):
        await update_key_fn(
            request=MagicMock(),
            data=UpdateKeyRequest(
                key=ACCESS_GROUP_SYNC_TOKEN, access_group_ids=added
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
        )

    assert [call.args[0] for call in raw_mock.call_args_list] == [
        _ATTACH_KEY_SQL,
        _DETACH_KEY_SQL,
    ]
    assert sorted(raw_mock.call_args_list[0].args[2]) == sorted(added)
    assert sorted(raw_mock.call_args_list[1].args[2]) == sorted(dropped)
    assert all(
        access_groups[group_id]["assigned_key_ids"] == [ACCESS_GROUP_SYNC_TOKEN]
        for group_id in added
    )
    assert all(access_groups[group_id]["assigned_key_ids"] == [] for group_id in dropped)


@pytest.mark.asyncio
async def test_regenerate_key_repoints_live_membership_not_the_key_row_it_read(
    monkeypatch,
):
    """
    Regeneration must move whatever the groups hold when it writes, not the key row's list.

    That list is read before the new token exists, so replaying it re-adds the key to a
    group an admin revoked in between and leaves the dead hash in a group an admin attached
    in between, which silently restores one grant and drops another.
    """
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )
    from litellm.proxy.utils import hash_token

    new_token_hash = hash_token("sk-newtoken1234ab12")
    existing_key = LiteLLM_VerificationToken(
        token="abc123",
        user_id="user-1",
        models=["gpt-4"],
        access_group_ids=["ag-revoked-since"],
    )
    access_groups = {
        "ag-revoked-since": {
            "assigned_key_ids": [],
            "access_model_names": ["revoked-model"],
        },
        "ag-attached-since": {
            "assigned_key_ids": ["abc123"],
            "access_model_names": ["attached-model"],
        },
    }

    mock_prisma_client = _make_regenerate_mock_prisma()
    _access_group_table_mocks(monkeypatch, mock_prisma_client, access_groups)

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_helpers.access_group_key_sync._invalidate_access_group_cache",
            new_callable=AsyncMock,
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert access_groups["ag-revoked-since"]["assigned_key_ids"] == []
    assert access_groups["ag-attached-since"]["assigned_key_ids"] == [new_token_hash]
    assert await _authorized_models_for_key(
        access_groups, new_token_hash, ["ag-revoked-since", "ag-attached-since"]
    ) == ["attached-model"]


async def _cache_with_project(
    project_id: str, project_models: list[str], team_id: str | None = "team-lit-5823"
) -> UserApiKeyCache:
    user_api_key_cache = UserApiKeyCache()
    await user_api_key_cache.async_set_cache(
        key=project_cache_key(project_id),
        value=LiteLLM_ProjectTableCachedObj(project_id=project_id, team_id=team_id, models=project_models),
        model_type=LiteLLM_ProjectTableCachedObj,
    )
    return user_api_key_cache


@pytest.mark.parametrize("request_cls", [GenerateKeyRequest, UpdateKeyRequest])
@pytest.mark.parametrize("sentinel", ["all-team-models", "all-proxy-models"])
@pytest.mark.asyncio
async def test_check_project_key_limits_accepts_inherited_model_sentinels(request_cls, sentinel):
    """LIT-5823: the sentinels inherit a parent scope, so a project allowlist must not treat them as model names."""
    user_api_key_cache = await _cache_with_project("proj-lit-5823", ["gpt-5.4-nano"])

    await _check_project_key_limits(
        project_id="proj-lit-5823",
        data=request_cls(key="sk-lit-5823", models=[sentinel]),
        prisma_client=MagicMock(),
        user_api_key_cache=user_api_key_cache,
    )


@pytest.mark.parametrize("request_cls", [GenerateKeyRequest, UpdateKeyRequest])
@pytest.mark.parametrize(
    "key_models",
    [["gpt-5.4-mini"], ["all-team-models", "gpt-5.4-mini"], ["gpt-5.4-nano", "all-proxy-models", "gpt-5.4-mini"]],
)
@pytest.mark.asyncio
async def test_check_project_key_limits_still_rejects_real_model_outside_project(request_cls, key_models):
    user_api_key_cache = await _cache_with_project("proj-lit-5823", ["gpt-5.4-nano"])

    with pytest.raises(HTTPException) as exc_info:
        await _check_project_key_limits(
            project_id="proj-lit-5823",
            data=request_cls(key="sk-lit-5823", models=key_models),
            prisma_client=MagicMock(),
            user_api_key_cache=user_api_key_cache,
        )

    assert exc_info.value.status_code == 400
    assert "Model 'gpt-5.4-mini' not in project's allowed models" in exc_info.value.detail["error"]


@pytest.mark.asyncio
async def test_update_key_soft_budget_updates_existing_budget_row():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id="budget-123")
    mock_db = MagicMock()
    mock_db.litellm_budgettable.update = AsyncMock()
    mock_db.litellm_budgettable.create = AsyncMock()

    result = await _update_key_soft_budget(
        db=mock_db,
        existing_key_row=existing_key,
        soft_budget=25.0,
        changed_by="user-1",
    )

    assert result == "budget-123"
    mock_db.litellm_budgettable.update.assert_awaited_once_with(
        where={"budget_id": "budget-123"},
        data={"soft_budget": 25.0, "updated_by": "user-1"},
    )


@pytest.mark.asyncio
async def test_update_key_soft_budget_clears_existing_budget_row():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id="budget-123")
    mock_db = MagicMock()
    mock_db.litellm_budgettable.update = AsyncMock()
    mock_db.litellm_budgettable.create = AsyncMock()

    result = await _update_key_soft_budget(
        db=mock_db,
        existing_key_row=existing_key,
        soft_budget=None,
        changed_by="user-1",
    )

    assert result == "budget-123"
    mock_db.litellm_budgettable.update.assert_awaited_once_with(
        where={"budget_id": "budget-123"},
        data={"soft_budget": None, "updated_by": "user-1"},
    )


@pytest.mark.asyncio
async def test_update_key_soft_budget_creates_budget_row_when_key_has_none():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id=None)
    created_row = MagicMock()
    created_row.budget_id = "budget-new"
    mock_db = MagicMock()
    mock_db.litellm_budgettable.create = AsyncMock(return_value=created_row)
    mock_db.litellm_budgettable.update = AsyncMock()

    result = await _update_key_soft_budget(
        db=mock_db,
        existing_key_row=existing_key,
        soft_budget=10.5,
        changed_by="user-1",
    )

    assert result == "budget-new"
    mock_db.litellm_budgettable.create.assert_awaited_once_with(
        data={"soft_budget": 10.5, "created_by": "user-1", "updated_by": "user-1"}
    )


@pytest.mark.asyncio
async def test_update_key_soft_budget_noop_when_clearing_without_budget_row():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id=None)
    mock_db = MagicMock()
    mock_db.litellm_budgettable.create = AsyncMock()
    mock_db.litellm_budgettable.update = AsyncMock()

    result = await _update_key_soft_budget(
        db=mock_db,
        existing_key_row=existing_key,
        soft_budget=None,
        changed_by="user-1",
    )

    assert result is None
    mock_db.litellm_budgettable.create.assert_not_awaited()
    mock_db.litellm_budgettable.update.assert_not_awaited()


def test_update_key_request_accepts_soft_budget():
    request = UpdateKeyRequest(key="sk-test", soft_budget=42.0)
    assert request.soft_budget == 42.0
    assert "soft_budget" in request.model_fields_set


@pytest.mark.parametrize("valid_value", [None, 0.0, 25.0])
def test_validate_soft_budget_value_accepts_valid_values(valid_value):
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _validate_soft_budget_value,
    )

    assert _validate_soft_budget_value(valid_value) is None


@pytest.mark.parametrize("invalid_value", [-5.0, float("nan"), float("inf")])
def test_validate_soft_budget_value_rejects_invalid_values(invalid_value):
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _validate_soft_budget_value,
    )

    with pytest.raises(HTTPException) as exc_info:
        _validate_soft_budget_value(invalid_value)

    assert exc_info.value.status_code == 400
    assert "soft_budget must be a non-negative finite number" in str(exc_info.value.detail)


@pytest.mark.asyncio
async def test_apply_soft_budget_update_adds_budget_id_for_new_budget_row():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _apply_soft_budget_update,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id=None)
    created_row = MagicMock()
    created_row.budget_id = "budget-created-456"
    mock_db = MagicMock()
    mock_db.litellm_budgettable.create = AsyncMock(return_value=created_row)
    mock_db.litellm_budgettable.update = AsyncMock()

    result = await _apply_soft_budget_update(
        data=UpdateKeyRequest(key="sk-test", soft_budget=25.0),
        non_default_values={"soft_budget": 25.0},
        db=mock_db,
        existing_key_row=existing_key,
        changed_by="user-1",
    )

    assert dict(result) == {"budget_id": "budget-created-456"}


@pytest.mark.asyncio
async def test_apply_soft_budget_update_keeps_existing_budget_id_out_of_token_update():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _apply_soft_budget_update,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id="budget-123")
    mock_db = MagicMock()
    mock_db.litellm_budgettable.update = AsyncMock()
    mock_db.litellm_budgettable.create = AsyncMock()

    result = await _apply_soft_budget_update(
        data=UpdateKeyRequest(key="sk-test", soft_budget=40.0),
        non_default_values={"soft_budget": 40.0, "max_budget": 100.0},
        db=mock_db,
        existing_key_row=existing_key,
        changed_by="user-1",
    )

    assert dict(result) == {"max_budget": 100.0}
    mock_db.litellm_budgettable.update.assert_awaited_once_with(
        where={"budget_id": "budget-123"},
        data={"soft_budget": 40.0, "updated_by": "user-1"},
    )


@pytest.mark.asyncio
async def test_update_key_row_with_soft_budget_updates_budget_and_key_in_transaction():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_row_with_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id=None)
    created_row = MagicMock(budget_id="budget-new")
    updated_row = MagicMock()
    updated_row.model_dump.return_value = {
        "token": "hashed",
        "budget_id": "budget-new",
        "object_permission": {"mcp_servers": ["srv-1"], "mcp_tool_permissions": {"srv-1": ["read"]}},
    }
    tx = MagicMock()
    tx.litellm_budgettable.create = AsyncMock(return_value=created_row)
    tx.litellm_verificationtoken.update = AsyncMock(return_value=updated_row)
    tx_context = MagicMock()
    tx_context.__aenter__ = AsyncMock(return_value=tx)
    tx_context.__aexit__ = AsyncMock(return_value=None)
    prisma_client = MagicMock()
    prisma_client.tx.return_value = tx_context
    prisma_client.jsonify_object = lambda data: dict(data)

    result = await _update_key_row_with_soft_budget(
        prisma_client=prisma_client,
        key="sk-test",
        data=UpdateKeyRequest(key="sk-test", soft_budget=25.0),
        non_default_values={"soft_budget": 25.0},
        existing_key_row=existing_key,
        changed_by="user-1",
    )

    assert set(result) == {"token", "data"}
    assert result["data"] == {
        "token": "hashed",
        "budget_id": "budget-new",
        "object_permission": {"mcp_servers": ["srv-1"], "mcp_tool_permissions": {"srv-1": ["read"]}},
    }
    tx.litellm_verificationtoken.update.assert_awaited_once()
    update_call = tx.litellm_verificationtoken.update.await_args
    assert update_call.kwargs["where"] == {"token": result["token"]}
    assert update_call.kwargs["include"] == {"object_permission": True}
    assert update_call.kwargs["data"]["budget_id"] == "budget-new"
    assert "soft_budget" not in update_call.kwargs["data"]


@pytest.mark.asyncio
async def test_update_key_row_with_soft_budget_propagates_transaction_error():
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _update_key_row_with_soft_budget,
    )

    existing_key = LiteLLM_VerificationToken(token="test-token", budget_id=None)
    created_row = MagicMock(budget_id="budget-new")
    tx = MagicMock()
    tx.litellm_budgettable.create = AsyncMock(return_value=created_row)
    tx.litellm_verificationtoken.update = AsyncMock(side_effect=RuntimeError("update failed"))
    tx_context = MagicMock()
    tx_context.__aenter__ = AsyncMock(return_value=tx)
    tx_context.__aexit__ = AsyncMock(return_value=None)
    prisma_client = MagicMock()
    prisma_client.tx.return_value = tx_context
    prisma_client.jsonify_object = lambda data: dict(data)

    with pytest.raises(RuntimeError, match="update failed"):
        await _update_key_row_with_soft_budget(
            prisma_client=prisma_client,
            key="sk-test",
            data=UpdateKeyRequest(key="sk-test", soft_budget=25.0),
            non_default_values={"soft_budget": 25.0},
            existing_key_row=existing_key,
            changed_by="user-1",
        )

    tx_context.__aexit__.assert_awaited_once()
    assert tx_context.__aexit__.await_args.args[0] is RuntimeError


def test_generate_key_request_blank_team_id_is_personal():
    """The UI Team-field clear submits team_id=""; it must count as no team (LIT-3925)."""
    from litellm.proxy._types import RegenerateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _is_team_key,
    )

    cleared = GenerateKeyRequest(team_id="")
    assert cleared.team_id is None
    assert _is_team_key(data=cleared) is False
    assert RegenerateKeyRequest(team_id="").team_id is None
    assert GenerateKeyRequest(team_id="team-1").team_id == "team-1"


def test_generate_key_request_blank_organization_and_project_id_are_unset():
    from litellm.proxy._types import RegenerateKeyRequest

    cleared = GenerateKeyRequest(organization_id="", project_id="")
    assert cleared.organization_id is None
    assert cleared.project_id is None
    assert "organization_id" not in cleared.model_dump(exclude_none=True)
    assert RegenerateKeyRequest(organization_id="").organization_id is None
    assert GenerateKeyRequest(organization_id="org-1", project_id="proj-1").organization_id == "org-1"
    assert GenerateKeyRequest(organization_id="org-1", project_id="proj-1").project_id == "proj-1"


def test_key_request_blank_organization_id_is_unset():
    from litellm.proxy._types import RegenerateKeyRequest, UpdateKeyRequest

    assert GenerateKeyRequest(organization_id="").organization_id is None
    assert RegenerateKeyRequest(organization_id="").organization_id is None
    assert UpdateKeyRequest(key="sk-1", organization_id="").organization_id is None
    assert GenerateKeyRequest(organization_id="org-1").organization_id == "org-1"
    assert UpdateKeyRequest(key="sk-1", organization_id="org-1").organization_id == "org-1"


def test_update_key_request_blank_team_id_is_not_a_team_change():
    from litellm.proxy._types import UpdateKeyRequest
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        is_different_team,
    )

    blank = UpdateKeyRequest(key="sk-1", team_id="", key_alias="renamed")
    assert blank.team_id is None
    assert "team_id" not in blank.model_dump(exclude_unset=True)
    assert blank.model_dump(exclude_unset=True) == {"key": "sk-1", "key_alias": "renamed"}
    assert is_different_team(data=blank, existing_key_row=LiteLLM_VerificationToken(token="hashed")) is False
    assert (
        is_different_team(data=blank, existing_key_row=LiteLLM_VerificationToken(token="hashed", team_id="team-1"))
        is False
    )
    assert "team_id" in UpdateKeyRequest(key="sk-1", team_id=None).model_dump(exclude_unset=True)
    assert UpdateKeyRequest(key="sk-1", team_id="team-1").team_id == "team-1"
    assert (
        is_different_team(
            data=UpdateKeyRequest(key="sk-1", team_id="team-1"),
            existing_key_row=LiteLLM_VerificationToken(token="hashed"),
        )
        is True
    )


def test_key_generation_check_blank_team_id_uses_personal_permissions(monkeypatch):
    """key_generation_check with team_id="" must take the personal-key path instead
    of failing the team lookup with "Unable to find team object" (LIT-3925)."""
    from litellm.proxy._types import KeyManagementRoutes
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        key_generation_check,
    )

    monkeypatch.setattr(
        litellm,
        "key_generation_settings",
        {
            "team_key_generation": {"allowed_team_member_roles": ["admin"]},
            "personal_key_generation": {"allowed_user_roles": ["proxy_admin", "internal_user"]},
        },
    )

    assert (
        key_generation_check(
            team_table=None,
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-alice",
                user_id="alice",
            ),
            data=GenerateKeyRequest(key_alias="personal", team_id=""),
            route=KeyManagementRoutes.KEY_GENERATE,
        )
        is True
    )


@pytest.mark.asyncio
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"


@pytest.mark.parametrize("project_id", [None, "project-orbit", "project-other", ""])
@pytest.mark.asyncio
async def test_project_detachment_uses_effective_project_for_validation_on_unowned_project(
    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"], team_id=None)
    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
        expected: Final = "not in project's allowed models" if project_id == "project-orbit" else "reassignment"
        assert expected in str(exc.value.detail)


@pytest.mark.asyncio
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)


_OWNED_PROJECT: Final = "proj-owned-1"
_OWNERSHIP_PROJECT_TEAM: Final = "ownership-project-team"
_OWNERSHIP_KEY_TEAM: Final = "ownership-key-team"
_OWNERSHIP_DESTINATION_TEAM: Final = "ownership-destination-team"


def _make_generate_mock_prisma() -> AsyncMock:
    mock_prisma_client: Final = AsyncMock()
    mock_prisma_client.insert_data = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None, object_permission=None)
    )
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken = MagicMock()
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma_client.db.litellm_verificationtoken.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_verificationtoken.count = AsyncMock(return_value=0)
    mock_prisma_client.db.litellm_verificationtoken.update = AsyncMock(
        return_value=MagicMock(token="hashed_token_123", litellm_budget_table=None, object_permission=None)
    )
    mock_prisma_client.db.litellm_teamtable = MagicMock()
    mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=None)
    return mock_prisma_client


def _configure_key_endpoints(
    monkeypatch: pytest.MonkeyPatch,
    user_api_key_cache: UserApiKeyCache,
) -> AsyncMock:
    mock_prisma_client: Final = _make_generate_mock_prisma()
    project_obj: Final = user_api_key_cache.get_cache(
        key=project_cache_key(_OWNED_PROJECT),
        model_type=LiteLLM_ProjectTableCachedObj,
    )
    project_row: Final = (
        LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=project_obj.team_id)
        if project_obj is not None
        else None
    )
    mock_prisma_client.db.litellm_projecttable = MagicMock()
    mock_prisma_client.db.litellm_projecttable.find_unique = AsyncMock(
        return_value=project_row
    )
    mock_prisma_client.writer_db = MagicMock()
    mock_prisma_client.writer_db.litellm_teamtable = mock_prisma_client.db.litellm_teamtable
    mock_prisma_client.writer_db.litellm_projecttable = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=project_row
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", user_api_key_cache)
    return mock_prisma_client


@pytest.mark.parametrize("key_team_id", ["team-a", None])
@pytest.mark.asyncio
async def test_key_generation_rejects_foreign_project_team(
    monkeypatch: pytest.MonkeyPatch,
    key_team_id: str | None,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id="team-b")
    _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    with pytest.raises(HTTPException) as error:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(project_id=_OWNED_PROJECT, team_id=key_team_id),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
            litellm_changed_by=None,
            team_table=None,
        )

    expected_detail: Final = {
        "error": (
            f"Project {_OWNED_PROJECT} belongs to team team-b, but the key belongs to "
            f"{key_team_id if key_team_id is not None else 'no team'}. "
            "A key can only be attached to a project owned by its own team."
        )
    }
    assert error.value.status_code == 400
    assert error.value.detail == expected_detail


@pytest.mark.asyncio
async def test_key_generation_budget_ceiling_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM)
    _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    with pytest.raises(HTTPException) as error:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                project_id=_OWNED_PROJECT,
                team_id=_OWNERSHIP_KEY_TEAM,
                max_budget=10,
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="litellm_login_session",
                user_id="session-user",
                team_id=_OWNERSHIP_KEY_TEAM,
                is_session_token=True,
                max_budget=5,
            ),
            litellm_changed_by=None,
            team_table=LiteLLM_TeamTableCachedObj(team_id=_OWNERSHIP_KEY_TEAM),
        )

    assert error.value.status_code == 400
    assert error.value.detail == {"error": "max_budget (10.0) cannot exceed the caller's own max_budget (5.0)."}


@pytest.mark.asyncio
async def test_key_generation_organization_membership_error_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(
        _OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM
    )
    mock_prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    mock_prisma_client.db.litellm_usertable = MagicMock()
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(user_id="key-owner", organization_memberships=[])
    )
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    with pytest.raises(HTTPException) as error:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                project_id=_OWNED_PROJECT,
                organization_id="org-not-member",
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-user",
                user_id="key-owner",
                is_session_token=True,
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    assert error.value.status_code == 403
    assert error.value.detail == "Caller is not a member of organization_id=org-not-member"


@pytest.mark.asyncio
async def test_key_generation_premium_permission_error_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(
        _OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM
    )
    mock_prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", None)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)

    with pytest.raises(HTTPException) as error:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                project_id=_OWNED_PROJECT,
                team_id=_OWNERSHIP_KEY_TEAM,
                permissions={"get_spend_routes": True},
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
            ),
            litellm_changed_by=None,
            team_table=None,
        )

    assert error.value.status_code == 500
    assert error.value.detail == {"error": "Internal Server Error."}
    mock_prisma_client.insert_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_key_generation_duplicate_alias_error_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    key_alias: Final = "duplicate-alias"
    user_api_key_cache: Final = await _cache_with_project(
        _OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM
    )
    mock_prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    mock_prisma_client.db.litellm_verificationtoken.find_first = AsyncMock(
        return_value=LiteLLM_VerificationToken(token="existing-token", key_alias=key_alias)
    )
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    with pytest.raises(ProxyException) as error:
        await _common_key_generation_helper(
            data=GenerateKeyRequest(
                project_id=_OWNED_PROJECT,
                team_id=_OWNERSHIP_KEY_TEAM,
                key_alias=key_alias,
            ),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
            litellm_changed_by=None,
            team_table=None,
        )

    assert error.value.code == "400"
    assert error.value.message == (
        f"Key with alias '{key_alias}' already exists. Unique key aliases across all keys are required."
    )
    mock_prisma_client.insert_data.assert_not_awaited()


@pytest.mark.parametrize(
    ("key_team_id", "expected_status"),
    [(_OWNERSHIP_PROJECT_TEAM, 200), (_OWNERSHIP_KEY_TEAM, 400)],
)
@pytest.mark.asyncio
async def test_key_generation_uses_database_project_team_when_cache_is_stale(
    monkeypatch: pytest.MonkeyPatch,
    key_team_id: str,
    expected_status: int,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id=_OWNERSHIP_KEY_TEAM)
    prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    prisma_client.db.litellm_projecttable = MagicMock()
    prisma_client.db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_KEY_TEAM)
    )
    prisma_client.writer_db.litellm_projecttable = MagicMock()
    prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)
    )
    monkeypatch.setattr(litellm, "default_key_generate_params", None)
    data: Final = GenerateKeyRequest(project_id=_OWNED_PROJECT, team_id=key_team_id)
    user_api_key_dict: Final = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin")

    if expected_status == 200:
        response: Final = await _common_key_generation_helper(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            team_table=None,
        )
        assert response.team_id == _OWNERSHIP_PROJECT_TEAM
        return

    with pytest.raises(HTTPException) as error:
        await _common_key_generation_helper(
            data=data,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
            team_table=None,
        )

    expected_detail: Final = {
        "error": (
            f"Project {_OWNED_PROJECT} belongs to team {_OWNERSHIP_PROJECT_TEAM}, but the key belongs to "
            f"{_OWNERSHIP_KEY_TEAM}. A key can only be attached to a project owned by its own team."
        )
    }
    assert error.value.status_code == 400
    assert error.value.detail == expected_detail


@pytest.mark.asyncio
async def test_key_generation_slow_writer_project_lookup_does_not_stall_db_tracker(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM)
    prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr("litellm.proxy.db.db_lookup_gate.PROXY_DB_LOOKUP_DEADLINE_SECONDS", 0.0)

    async def slow_project_lookup(*, where: Mapping[str, object]) -> LiteLLM_ProjectTable:
        assert where == {"project_id": _OWNED_PROJECT}
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        return LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)

    prisma_client.writer_db.litellm_projecttable.find_unique = slow_project_lookup
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    db_lookup_stall_tracker.clear()
    try:
        response: Final = await asyncio.wait_for(
            _common_key_generation_helper(
                data=GenerateKeyRequest(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM),
                user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
                litellm_changed_by=None,
                team_table=None,
            ),
            timeout=1.0,
        )
        assert response.team_id == _OWNERSHIP_PROJECT_TEAM
        assert db_lookup_stall_tracker.stalled_within(PROXY_DB_LOOKUP_STALL_WINDOW_SECONDS) is False
    finally:
        db_lookup_stall_tracker.clear()


@pytest.mark.parametrize("project_team_id", ["team-a", None])
@pytest.mark.asyncio
async def test_key_generation_accepts_same_team_and_unowned_projects(
    monkeypatch: pytest.MonkeyPatch,
    project_team_id: str | None,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(
        _OWNED_PROJECT, [], team_id=project_team_id
    )
    _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", None)

    response: Final = await _common_key_generation_helper(
        data=GenerateKeyRequest(project_id=_OWNED_PROJECT, team_id="team-a"),
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
        litellm_changed_by=None,
        team_table=None,
    )

    assert response.team_id == "team-a"


@pytest.mark.parametrize(("project_team_id", "expected_status"), [("team-b", None), ("team-c", 400)])
@pytest.mark.asyncio
async def test_key_generation_uses_default_team_for_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
    project_team_id: str,
    expected_status: int | None,
) -> None:
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id=project_team_id)
    _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", {"team_id": "team-b"})
    data: Final = GenerateKeyRequest(project_id=_OWNED_PROJECT)

    if expected_status is not None:
        with pytest.raises(HTTPException) as error:
            await _common_key_generation_helper(
                data=data,
                user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
                litellm_changed_by=None,
                team_table=None,
            )
        assert error.value.status_code == expected_status
        assert "belongs to team team-c, but the key belongs to team-b" in str(error.value.detail)
        return

    response: Final = await _common_key_generation_helper(
        data=data,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
        litellm_changed_by=None,
        team_table=None,
    )
    assert response.team_id == "team-b"


@pytest.mark.asyncio
async def test_service_account_generation_rejects_foreign_project_team(monkeypatch: pytest.MonkeyPatch) -> None:
    team_id: Final = "service-account-team"
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id="team-b")
    mock_prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
        return_value=LiteLLM_TeamTable(team_id=team_id)
    )

    with pytest.raises(HTTPException) as error:
        await generate_service_account_key_fn(
            data=GenerateKeyRequest(team_id=team_id, project_id=_OWNED_PROJECT),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
            litellm_changed_by=None,
        )

    assert error.value.status_code == 400
    assert "belongs to team team-b, but the key belongs to service-account-team" in str(
        error.value.detail
    )


@pytest.mark.asyncio
async def test_key_generation_default_budget_does_not_reject_project_budget(monkeypatch: pytest.MonkeyPatch) -> None:
    user_api_key_cache: Final = UserApiKeyCache()
    project: Final = LiteLLM_ProjectTableCachedObj(
        project_id=_OWNED_PROJECT,
        team_id="team-a",
        models=[],
        litellm_budget_table=LiteLLM_BudgetTable(max_budget=1.0),
    )
    await user_api_key_cache.async_set_cache(
        key=project_cache_key(_OWNED_PROJECT),
        value=project,
        model_type=LiteLLM_ProjectTableCachedObj,
    )
    _configure_key_endpoints(monkeypatch, user_api_key_cache)
    monkeypatch.setattr(litellm, "default_key_generate_params", {"team_id": "team-a", "max_budget": 10.0})

    response: Final = await generate_key_fn(
        data=GenerateKeyRequest(project_id=_OWNED_PROJECT),
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
    )

    assert response.team_id == "team-a"


@pytest.mark.asyncio
async def test_key_update_rejects_team_change_for_project_bound_key(monkeypatch: pytest.MonkeyPatch) -> None:
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-key",
        team_id=_OWNERSHIP_KEY_TEAM,
        project_id=_OWNED_PROJECT,
        object_permission_id="permission-update",
        budget_id="budget-update",
    )
    mock_prisma_client: Final = _wire_update_key_fn(monkeypatch, existing_key_row)
    existing_permission: Final = LiteLLM_ObjectPermissionTable(
        object_permission_id="permission-update",
        vector_stores=["existing-store"],
    )
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=existing_permission)
    permission_upsert: Final = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert
    permission_before: Final = existing_permission.model_dump()
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        AsyncMock(
            return_value=LiteLLM_TeamTable(team_id=_OWNERSHIP_DESTINATION_TEAM).model_copy(
                update={"team_members": []}
            )
        ),
    )
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", MagicMock())
    mock_request: Final = MagicMock()
    mock_request.query_params = {}

    with pytest.raises((HTTPException, ProxyException)) as error:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(
                key="sk-key",
                team_id=_OWNERSHIP_DESTINATION_TEAM,
                soft_budget=5.0,
                object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["replacement-store"]),
            ),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
            litellm_changed_by=None,
        )

    assert str(getattr(error.value, "status_code", None) or getattr(error.value, "code", None)) == "400"
    expected_detail: Final = (
        f"Project {_OWNED_PROJECT} belongs to team {_OWNERSHIP_PROJECT_TEAM}, "
        f"but the key belongs to {_OWNERSHIP_DESTINATION_TEAM}"
    )
    assert expected_detail in str(getattr(error.value, "detail", None) or getattr(error.value, "message", None))
    assert existing_permission.model_dump() == permission_before
    permission_upsert.assert_not_awaited()
    mock_prisma_client.tx.assert_not_called()
    mock_prisma_client.update_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_key_update_ambiguous_permission_error_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-key",
        team_id=_OWNERSHIP_KEY_TEAM,
        project_id=_OWNED_PROJECT,
        object_permission_id="permission-ambiguous",
    )
    mock_prisma_client: Final = _wire_update_key_fn(monkeypatch, existing_key_row)
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(
        return_value=LiteLLM_ObjectPermissionTable(
            object_permission_id="permission-ambiguous",
            mcp_tool_permissions={},
        )
    )
    permission_upsert: Final = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert
    mock_prisma_client.db.litellm_mcpservertable.find_many = AsyncMock(
        return_value=[
            MagicMock(server_id="wiki-a-id", alias="wiki", server_name="wiki-a"),
            MagicMock(server_id="wiki-b-id", alias="wiki", server_name="wiki-b"),
        ]
    )
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)
    )
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        AsyncMock(
            return_value=LiteLLM_TeamTable(
                team_id=_OWNERSHIP_DESTINATION_TEAM,
                object_permission=LiteLLM_ObjectPermissionTable(
                    object_permission_id="permission-team",
                    mcp_servers=["wiki-a-id", "wiki-b-id"],
                ),
            )
        ),
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", MagicMock())

    with pytest.raises((HTTPException, ProxyException)) as error:
        await update_key_fn(
            request=MagicMock(query_params={}),
            data=UpdateKeyRequest(
                key="sk-key",
                team_id=_OWNERSHIP_DESTINATION_TEAM,
                object_permission=LiteLLM_ObjectPermissionBase(
                    mcp_tool_permissions={"wiki": ["read_wiki_structure"]}
                ),
            ),
            user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-admin"),
            litellm_changed_by=None,
        )

    assert str(getattr(error.value, "status_code", None) or getattr(error.value, "code", None)) == "400"
    expected_detail: Final = {
        "error": (
            "Ambiguous mcp_tool_permissions key: 'wiki' matches MCP servers ['wiki-a-id', 'wiki-b-id']. "
            "Key tool permissions by server_id when servers share a name or alias."
        )
    }
    assert getattr(error.value, "detail", None) == expected_detail or getattr(error.value, "message", None) == str(
        expected_detail
    )
    permission_upsert.assert_not_awaited()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique.assert_not_awaited()
    mock_prisma_client.update_data.assert_not_awaited()


@pytest.mark.asyncio
async def test_key_update_organization_membership_error_precedes_project_ownership(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-key",
        user_id="key-owner",
        created_by="key-owner",
        team_id=_OWNERSHIP_PROJECT_TEAM,
        project_id=_OWNED_PROJECT,
    )
    mock_prisma_client: Final = _wire_update_key_fn(monkeypatch, existing_key_row)
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM)
    monkeypatch.setattr("litellm.proxy.proxy_server.user_api_key_cache", user_api_key_cache)
    mock_prisma_client.db.litellm_usertable = MagicMock()
    mock_prisma_client.db.litellm_usertable.find_unique = AsyncMock(
        return_value=LiteLLM_UserTable(user_id="key-owner", organization_memberships=[])
    )
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)
    )
    team_object: Final = LiteLLM_TeamTableCachedObj(
        team_id=_OWNERSHIP_KEY_TEAM,
        members_with_roles=[Member(user_id="key-owner", role="admin")],
        team_member_permissions=["/key/update"],
    )
    team_lookup: Final = AsyncMock(return_value=team_object)
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
        team_lookup,
    )
    monkeypatch.setattr(
        "litellm.proxy.management_helpers.team_member_permission_checks.get_team_object",
        team_lookup,
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", MagicMock())
    mock_request: Final = MagicMock()
    mock_request.query_params = {}

    with pytest.raises(ProxyException) as error:
        await update_key_fn(
            request=mock_request,
            data=UpdateKeyRequest(
                key="sk-key",
                team_id=_OWNERSHIP_KEY_TEAM,
                organization_id="org-not-member",
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-user",
                user_id="key-owner",
                team_id=_OWNERSHIP_PROJECT_TEAM,
            ),
            litellm_changed_by=None,
        )

    assert error.value.code == "403"
    assert error.value.message == "Caller is not a member of organization_id=org-not-member"


@pytest.mark.asyncio
async def test_bulk_key_update_rejects_project_team_change_and_allows_other_fields(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy.management_endpoints.key_management_endpoints import bulk_update_keys
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateKeyRequest,
        BulkUpdateKeyRequestItem,
    )

    user_api_key_cache: Final = await _cache_with_project(
        _OWNED_PROJECT, [], team_id=_OWNERSHIP_PROJECT_TEAM
    )
    mock_prisma_client: Final = _configure_key_endpoints(monkeypatch, user_api_key_cache)
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-bulk-key",
        user_id=None,
        models=[],
        team_id=_OWNERSHIP_PROJECT_TEAM,
        project_id=_OWNED_PROJECT,
        object_permission_id="permission-bulk",
        budget_id="budget-bulk",
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing_key_row)
    mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
        return_value=LiteLLM_TeamTable(team_id=_OWNERSHIP_DESTINATION_TEAM)
    )
    existing_permission: Final = LiteLLM_ObjectPermissionTable(
        object_permission_id="permission-bulk",
        vector_stores=["existing-store"],
    )
    permission_before: Final = existing_permission.model_dump()
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(return_value=existing_permission)
    permission_upsert: Final = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert
    budget_update: Final = AsyncMock()
    mock_prisma_client.db.litellm_budgettable.update = budget_update
    mock_prisma_client.get_data = AsyncMock(return_value=existing_key_row)
    updated_key: Final = MagicMock()
    updated_key.model_dump.return_value = {
        "max_budget": 10.0,
        "tags": ["bulk-update"],
        "team_id": _OWNERSHIP_PROJECT_TEAM,
        "project_id": _OWNED_PROJECT,
    }
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_key})
    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", MagicMock())
    monkeypatch.setattr("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock())

    request: Final = BulkUpdateKeyRequest(
        keys=[
            BulkUpdateKeyRequestItem.model_validate(
                {
                    "key": "sk-bulk-key",
                    "team_id": _OWNERSHIP_DESTINATION_TEAM,
                    "soft_budget": 5.0,
                    "object_permission": LiteLLM_ObjectPermissionBase(vector_stores=["replacement-store"]),
                }
            ),
            BulkUpdateKeyRequestItem(key="sk-bulk-key", max_budget=10.0, tags=["bulk-update"]),
        ]
    )
    user_api_key_dict: Final = UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
        api_key="sk-admin",
        user_id="admin",
    )

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
            new_callable=AsyncMock,
            return_value=LiteLLM_TeamTable(team_id=_OWNERSHIP_DESTINATION_TEAM),
        ),
        patch("litellm.proxy.management_endpoints.common_utils.premium_user_check"),
        patch("litellm.proxy.utils.premium_user_check"),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks",
            SimpleNamespace(async_key_updated_hook=AsyncMock()),
        ),
    ):
        response: Final = await bulk_update_keys(
            data=request,
            user_api_key_dict=user_api_key_dict,
            litellm_changed_by=None,
        )

    assert response.total_requested == 2
    assert [(item.key, item.failed_reason) for item in response.failed_updates] == [
        (
            "sk-bulk-key",
            (
                f"Project {_OWNED_PROJECT} belongs to team {_OWNERSHIP_PROJECT_TEAM}, but the key belongs to "
                f"{_OWNERSHIP_DESTINATION_TEAM}. A key can only be attached to a project owned by its own team."
            ),
        )
    ]
    assert len(response.successful_updates) == 1
    assert response.successful_updates[0].key == "sk-bulk-key"
    assert response.successful_updates[0].key_info["max_budget"] == 10.0
    assert response.successful_updates[0].key_info["tags"] == ["bulk-update"]
    assert existing_permission.model_dump() == permission_before
    permission_upsert.assert_not_awaited()
    budget_update.assert_not_awaited()
    mock_prisma_client.tx.assert_not_called()
    mock_prisma_client.update_data.assert_awaited_once()


@pytest.mark.parametrize(
    "request_fields",
    [{"key_alias": "renamed"}, {"team_id": _OWNERSHIP_KEY_TEAM}],
)
@pytest.mark.asyncio
async def test_key_team_ownership_mutation_allows_legacy_mismatch_without_changes(
    request_fields: dict[str, str],
) -> None:
    prisma_client: Final = MagicMock()
    prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(
            project_id=_OWNED_PROJECT,
            team_id=_OWNERSHIP_PROJECT_TEAM,
        )
    )
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-key",
        team_id=_OWNERSHIP_KEY_TEAM,
        project_id=_OWNED_PROJECT,
    )

    project_team_id: Final = await _check_key_project_team_on_mutation(
        data=UpdateKeyRequest(key="sk-key", **request_fields),
        existing_key_row=existing_key_row,
        prisma_client=prisma_client,
    )

    assert project_team_id is None


@pytest.mark.asyncio
async def test_key_team_ownership_mutation_allows_detach_with_team_change() -> None:
    prisma_client: Final = MagicMock()
    prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(
            project_id=_OWNED_PROJECT,
            team_id=_OWNERSHIP_PROJECT_TEAM,
        )
    )
    existing_key_row: Final = LiteLLM_VerificationToken(
        token="hashed-key",
        team_id=_OWNERSHIP_KEY_TEAM,
        project_id=_OWNED_PROJECT,
    )

    project_team_id: Final = await _check_key_project_team_on_mutation(
        data=UpdateKeyRequest(key="sk-key", project_id=None, team_id="team-b"),
        existing_key_row=existing_key_row,
        prisma_client=prisma_client,
    )

    assert project_team_id is None


@pytest.mark.parametrize(
    ("key_team_id", "expected_status", "expected_updates"),
    [("team-a", 400, 0), ("team-b", None, 1)],
)
@pytest.mark.asyncio
async def test_regenerate_checks_project_team_ownership(
    key_team_id: str,
    expected_status: int | None,
    expected_updates: int,
) -> None:
    existing_key: Final = LiteLLM_VerificationToken(
        token="abc123",
        team_id=key_team_id,
        object_permission_id="permission-regenerate",
    )
    mock_prisma_client: Final = _make_regenerate_mock_prisma()
    mock_prisma_client.writer_db = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id="team-b")
    )
    deleted_history_table: Final = MagicMock()
    deleted_history_table.create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken = deleted_history_table
    deprecated_key_table: Final = MagicMock()
    deprecated_key_table.upsert = AsyncMock()
    mock_prisma_client.db.litellm_deprecatedverificationtoken = deprecated_key_table
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(
        return_value=LiteLLM_ObjectPermissionTable(
            object_permission_id="permission-regenerate",
            vector_stores=["existing-store"],
        )
    )
    permission_upsert: Final = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = permission_upsert
    user_api_key_cache: Final = await _cache_with_project(_OWNED_PROJECT, [], team_id="team-b")

    async def regenerate() -> None:
        with (
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
                new_callable=AsyncMock,
                return_value="sk-newtoken1234ab12",
            ),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
                new_callable=AsyncMock,
            ),
        ):
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=existing_key,
                hashed_api_key="abc123",
                key="abc123",
                data=RegenerateKeyRequest(
                    project_id=_OWNED_PROJECT,
                    grace_period="1h" if expected_status is not None else None,
                    object_permission=LiteLLM_ObjectPermissionBase(vector_stores=["replacement-store"]),
                ),
                user_api_key_dict=_make_regenerate_user_api_key_dict(),
                litellm_changed_by=None,
                user_api_key_cache=user_api_key_cache,
                proxy_logging_obj=MagicMock(),
            )

    if expected_status is not None:
        with pytest.raises(HTTPException) as error:
            await regenerate()
        assert error.value.status_code == expected_status
        assert "belongs to team team-b, but the key belongs to team-a" in str(error.value.detail)
        deleted_history_table.create_many.assert_not_awaited()
        deprecated_key_table.upsert.assert_not_awaited()
        permission_upsert.assert_not_awaited()
    else:
        await regenerate()
        permission_upsert.assert_awaited_once()

    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == expected_updates


@pytest.mark.parametrize(
    ("caller_role", "expected_status", "expected_updates"),
    [(None, 403, 0), ("user", None, 1), ("admin", None, 1)],
)
@pytest.mark.asyncio
async def test_regenerate_requires_caller_in_project_team(
    caller_role: str | None,
    expected_status: int | None,
    expected_updates: int,
) -> None:
    existing_key: Final = LiteLLM_VerificationToken(token="abc123", user_id="caller-user", team_id=None)
    mock_prisma_client: Final = _make_regenerate_mock_prisma()
    mock_prisma_client.writer_db = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id="team-b")
    )
    deleted_history_table: Final = MagicMock()
    deleted_history_table.create_many = AsyncMock()
    mock_prisma_client.db.litellm_deletedverificationtoken = deleted_history_table
    project_team: Final = LiteLLM_TeamTableCachedObj(
        team_id="team-b",
        members_with_roles=[] if caller_role is None else [Member(user_id="caller-user", role=caller_role)],
    )
    get_team: Final = AsyncMock(return_value=project_team)

    async def regenerate() -> None:
        with (
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
                new_callable=AsyncMock,
                return_value="sk-newtoken1234ab12",
            ),
            patch(
                "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
                new_callable=AsyncMock,
            ),
            patch("litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", get_team),
        ):
            await _execute_virtual_key_regeneration(
                prisma_client=mock_prisma_client,
                key_in_db=existing_key,
                hashed_api_key="abc123",
                key="abc123",
                data=RegenerateKeyRequest(team_id="team-b", project_id=_OWNED_PROJECT),
                user_api_key_dict=UserAPIKeyAuth(
                    user_role=LitellmUserRoles.INTERNAL_USER,
                    api_key="sk-caller",
                    user_id="caller-user",
                ),
                litellm_changed_by=None,
                user_api_key_cache=UserApiKeyCache(),
                proxy_logging_obj=MagicMock(),
            )

    if expected_status is not None:
        with pytest.raises(HTTPException) as error:
            await regenerate()
        assert error.value.status_code == expected_status
        assert error.value.detail == {
            "error": "Only a proxy admin or a member of team team-b can attach a key to a project owned by that team."
        }
        deleted_history_table.create_many.assert_not_awaited()
    else:
        await regenerate()

    assert get_team.await_args.kwargs["team_id"] == "team-b"
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == expected_updates


@pytest.mark.asyncio
async def test_regenerate_proxy_admin_skips_project_team_membership_lookup() -> None:
    mock_prisma_client: Final = _make_regenerate_mock_prisma()
    mock_prisma_client.writer_db = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id="team-b")
    )
    get_team: Final = AsyncMock()

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch("litellm.proxy.management_endpoints.key_management_endpoints.get_team_object", get_team),
    ):
        response: Final = await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=LiteLLM_VerificationToken(token="abc123", user_id="user-1", team_id=None),
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(team_id="team-b", project_id=_OWNED_PROJECT),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=UserApiKeyCache(),
            proxy_logging_obj=MagicMock(),
        )

    assert response.key == "sk-newtoken1234ab12"
    get_team.assert_not_awaited()
    assert mock_prisma_client.db.litellm_verificationtoken.update.await_count == 1


@pytest.mark.asyncio
async def test_regenerate_output_estimate_admin_error_precedes_project_ownership() -> None:
    existing_key: Final = LiteLLM_VerificationToken(
        token="abc123",
        user_id="key-owner",
        team_id=_OWNERSHIP_PROJECT_TEAM,
        project_id=_OWNED_PROJECT,
        metadata={},
    )
    mock_prisma_client: Final = _make_regenerate_mock_prisma()
    mock_prisma_client.writer_db = MagicMock()
    mock_prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(
        return_value=LiteLLM_ProjectTable(project_id=_OWNED_PROJECT, team_id=_OWNERSHIP_PROJECT_TEAM)
    )

    with pytest.raises(HTTPException) as error:
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(
                project_id=_OWNED_PROJECT,
                team_id=_OWNERSHIP_KEY_TEAM,
                metadata={"default_estimated_output_tokens": 1},
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-user",
                user_id="key-owner",
            ),
            litellm_changed_by=None,
            user_api_key_cache=MagicMock(),
            proxy_logging_obj=MagicMock(),
        )

    assert error.value.status_code == 403
    assert "Only proxy admins can set" in str(error.value.detail)
    mock_prisma_client.db.litellm_verificationtoken.update.assert_not_awaited()


@pytest.mark.asyncio
async def test_key_project_team_validation_rejects_missing_project() -> None:
    prisma_client: Final = MagicMock()
    prisma_client.writer_db.litellm_projecttable.find_unique = AsyncMock(return_value=None)

    with pytest.raises(KeyProjectBindingError) as error:
        await _check_key_project_team(
            project_id=_OWNED_PROJECT,
            key_team_id="team-a",
            prisma_client=prisma_client,
        )

    assert error.value.status_code == 404
    assert error.value.detail == {"error": f"Project not found, project_id={_OWNED_PROJECT}"}


@pytest.mark.asyncio
async def test_bulk_update_team_keys_runs_custom_key_policy_per_key(monkeypatch):
    from litellm.types.proxy.management_endpoints.key_management_endpoints import (
        BulkUpdateTeamKeysRequest,
        KeyUpdateFields,
    )

    keys = [_make_team_key("tok-a"), _make_team_key("tok-b")]
    mock = _setup_team_keys_mocks(
        monkeypatch, find_many=keys, update_data=AsyncMock(return_value={"data": _updated({"max_budget": 50.0})})
    )
    received: list[CustomKeyPolicyRequest] = []

    async def freeze_tok_b(policy_request: CustomKeyPolicyRequest) -> dict[str, object]:
        received.append(policy_request)
        if policy_request.existing_key is not None and policy_request.existing_key.token == "tok-b":
            return {"decision": False, "message": "tok-b is frozen"}
        return {"decision": True}

    monkeypatch.setattr("litellm.proxy.proxy_server.user_custom_key_policy", freeze_tok_b)

    response = await _call_as_admin(
        BulkUpdateTeamKeysRequest(
            team_id="team-abc", key_ids=["tok-a", "tok-b"], update_fields=KeyUpdateFields(max_budget=50.0)
        )
    )

    assert [update.key for update in response.successful_updates] == ["tok-a"]
    assert [(failed.key, failed.failed_reason) for failed in response.failed_updates] == [("tok-b", "tok-b is frozen")]
    mock.update_data.assert_awaited_once()
    assert [policy_request.operation for policy_request in received] == ["update", "update"]
    assert [policy_request.effective_key.max_budget for policy_request in received] == [50.0, 50.0]
    assert [policy_request.effective_key.team_id for policy_request in received] == ["team-abc", "team-abc"]


class TestServiceAccountKeyGenerationCheck:
    """Service account keys (user_id=None, team_id set, metadata.service_account_id)
    may only create keys for their own team."""

    def _service_account_token(self, team_id: str) -> UserAPIKeyAuth:
        return UserAPIKeyAuth(
            api_key="sk-sa",
            user_id=None,
            team_id=team_id,
            metadata={"service_account_id": "sa-1"},
        )

    def test_other_team_denied(self):
        data = GenerateKeyRequest(team_id="team-b")
        with pytest.raises(HTTPException) as exc_info:
            key_generation_check(
                team_table=None,
                user_api_key_dict=self._service_account_token(team_id="team-a"),
                data=data,
                route=KeyManagementRoutes.KEY_GENERATE,
            )
        assert exc_info.value.status_code == 403

    def test_personal_key_denied(self):
        """team_id=None would mint a personal key; service accounts may only
        create keys for their own team."""
        data = GenerateKeyRequest()
        with pytest.raises(HTTPException) as exc_info:
            key_generation_check(
                team_table=None,
                user_api_key_dict=self._service_account_token(team_id="team-a"),
                data=data,
                route=KeyManagementRoutes.KEY_GENERATE,
            )
        assert exc_info.value.status_code == 403

    def test_own_team_with_permission_allowed(self):
        team_table = LiteLLM_TeamTableCachedObj(
            team_id="team-a",
            members_with_roles=[],
            team_member_permissions=["/key/generate"],
        )
        data = GenerateKeyRequest(team_id="team-a")
        assert (
            key_generation_check(
                team_table=team_table,
                user_api_key_dict=self._service_account_token(team_id="team-a"),
                data=data,
                route=KeyManagementRoutes.KEY_GENERATE,
            )
            is True
        )

    def test_own_team_without_permission_denied(self):
        team_table = LiteLLM_TeamTableCachedObj(
            team_id="team-a",
            members_with_roles=[],
            team_member_permissions=["/key/info"],
        )
        data = GenerateKeyRequest(team_id="team-a")
        with pytest.raises(ProxyException) as exc_info:
            key_generation_check(
                team_table=team_table,
                user_api_key_dict=self._service_account_token(team_id="team-a"),
                data=data,
                route=KeyManagementRoutes.KEY_GENERATE,
            )
        assert str(exc_info.value.code) == "401"


def _stub_service_account_generation(monkeypatch):
    """Stub the DB lookups generate_service_account_key_fn needs so the test
    exercises only the service_account_id stamping and user_id clearing."""
    from litellm.proxy import proxy_server
    from litellm.proxy.management_endpoints import key_management_endpoints as kme

    mock_helper = AsyncMock(return_value=MagicMock())
    monkeypatch.setattr(proxy_server, "prisma_client", MagicMock())
    monkeypatch.setattr(kme, "validate_team_id_used_in_service_account_request", AsyncMock())
    monkeypatch.setattr(kme, "_common_key_generation_helper", mock_helper)
    return mock_helper


@pytest.mark.asyncio
async def test_generate_service_account_key_stamps_service_account_id(monkeypatch):
    """generate_service_account_key_fn must stamp metadata.service_account_id
    (key_alias fallback) so the key is identifiable as a service account by
    is_team_service_account and check_if_token_is_service_account."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_service_account_key_fn,
    )

    mock_helper = _stub_service_account_generation(monkeypatch)
    data = GenerateKeyRequest(team_id="team-a", key_alias="sa-alias")

    await generate_service_account_key_fn(
        data=data,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
        litellm_changed_by=None,
    )

    assert data.metadata is not None
    assert data.metadata["service_account_id"] == "sa-alias"
    assert data.user_id is None
    mock_helper.assert_awaited_once()


@pytest.mark.asyncio
async def test_generate_service_account_key_generates_uuid_when_no_alias(monkeypatch):
    """Without key_alias, service_account_id falls back to a generated uuid."""
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        generate_service_account_key_fn,
    )

    _stub_service_account_generation(monkeypatch)
    data = GenerateKeyRequest(team_id="team-a")

    await generate_service_account_key_fn(
        data=data,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-1"),
        litellm_changed_by=None,
    )

    assert data.metadata is not None
    assert data.metadata["service_account_id"]

@pytest.mark.asyncio
async def test_key_update_invalidates_cached_object_permission(monkeypatch):
    """Regression: /key/update must drop the cached permission row, not just the cached key.

    The permission row is cached under its own id and the upsert keeps that id, so a key read
    after the update re-attached the OLD grants until the management-object TTL expired, which
    served revoked MCP tools and withheld newly granted ones.
    """
    from litellm.proxy._types import LiteLLM_ObjectPermissionBase
    from litellm.proxy.auth.auth_checks import get_object_permission
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache

    permission_id = "objperm-lit5479"
    grants = {"old": ["tool_a"], "new": ["tool_a", "tool_b"]}

    def _row(tools):
        row = MagicMock()
        row.dict.return_value = {
            "object_permission_id": permission_id,
            "mcp_tool_permissions": {"server-1": tools},
        }
        return row

    mock_prisma_client = AsyncMock()
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(
        side_effect=lambda **kwargs: _row(grants["old"])
    )
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = AsyncMock(
        return_value=MagicMock(object_permission_id=permission_id)
    )
    existing_key_row = LiteLLM_VerificationToken(
        token="hashed-sk-lit5479",
        user_id="user-123",
        object_permission_id=permission_id,
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(
        return_value=existing_key_row
    )
    updated_key = MagicMock()
    updated_key.model_dump.return_value = {"user_id": "user-123"}
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_key})
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    user_api_key_cache = UserApiKeyCache()
    assert (
        await get_object_permission(
            object_permission_id=permission_id,
            prisma_client=mock_prisma_client,
            user_api_key_cache=user_api_key_cache,
        )
    ).mcp_tool_permissions == {"server-1": grants["old"]}

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook"
    ):
        await _process_single_key_update(
            update_key_request=UpdateKeyRequest(
                key="sk-lit5479",
                object_permission=LiteLLM_ObjectPermissionBase(
                    mcp_tool_permissions={"server-1": grants["new"]}
                ),
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
            prisma_client=mock_prisma_client,
            user_api_key_cache=user_api_key_cache,
            proxy_logging_obj=AsyncMock(),
            llm_router=None,
            existing_key_row=existing_key_row,
        )

    mock_prisma_client.db.litellm_objectpermissiontable.find_unique.side_effect = (
        lambda **kwargs: _row(grants["new"])
    )
    reread = await get_object_permission(
        object_permission_id=permission_id,
        prisma_client=mock_prisma_client,
        user_api_key_cache=user_api_key_cache,
    )
    assert reread is not None
    assert reread.mcp_tool_permissions == {"server-1": grants["new"]}


@pytest.mark.asyncio
@pytest.mark.parametrize("key_has_permission", [True, False], ids=["existing-permission", "new-permission"])
async def test_key_regeneration_invalidates_cached_object_permission(
    monkeypatch: pytest.MonkeyPatch, key_has_permission: bool
):
    """Regression: regenerating a key with new permissions must not keep serving the old grants."""
    from litellm.proxy._types import LiteLLM_ObjectPermissionBase, RegenerateKeyRequest
    from litellm.proxy.auth.auth_checks import get_object_permission
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache, object_permission_cache_key
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        _execute_virtual_key_regeneration,
    )

    permission_id = str(UUID("00000000-0000-0000-0000-000000000002"))
    grants = {"served": ["tool_a"]}

    def _row(**kwargs):
        row = MagicMock()
        row.dict.return_value = {
            "object_permission_id": permission_id,
            "mcp_tool_permissions": {"server-1": grants["served"]},
        }
        return row

    mock_prisma_client = _make_regenerate_mock_prisma()
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(side_effect=_row)
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = AsyncMock(
        return_value=MagicMock(object_permission_id=permission_id)
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    monkeypatch.setattr(
        "litellm.proxy.management_helpers.object_permission_utils.uuid.uuid4",
        lambda: UUID(permission_id),
    )

    existing_key = _make_regenerate_existing_key()
    if key_has_permission:
        existing_key.object_permission_id = permission_id
    user_api_key_cache = UserApiKeyCache()
    assert (
        await get_object_permission(
            object_permission_id=permission_id,
            prisma_client=mock_prisma_client,
            user_api_key_cache=user_api_key_cache,
        )
    ).mcp_tool_permissions == {"server-1": ["tool_a"]}

    with (
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_new_token",
            new_callable=AsyncMock,
            return_value="sk-newtoken1234ab12",
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints._insert_deprecated_key",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.delete_cache_key_object",
            new_callable=AsyncMock,
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_rotated_hook"
        ),
    ):
        await _execute_virtual_key_regeneration(
            prisma_client=mock_prisma_client,
            key_in_db=existing_key,
            hashed_api_key="abc123",
            key="abc123",
            data=RegenerateKeyRequest(
                object_permission=LiteLLM_ObjectPermissionBase(mcp_tool_permissions={"server-1": ["tool_a", "tool_b"]})
            ),
            user_api_key_dict=_make_regenerate_user_api_key_dict(),
            litellm_changed_by=None,
            user_api_key_cache=user_api_key_cache,
            proxy_logging_obj=AsyncMock(),
        )

    assert (
        user_api_key_cache.get_cache(
            key=object_permission_cache_key(permission_id),
            model_type=LiteLLM_ObjectPermissionTable,
        )
        is None
    )
    grants["served"] = ["tool_a", "tool_b"]
    reread = await get_object_permission(
        object_permission_id=permission_id,
        prisma_client=mock_prisma_client,
        user_api_key_cache=user_api_key_cache,
    )
    assert reread is not None
    assert reread.mcp_tool_permissions == {"server-1": ["tool_a", "tool_b"]}


@pytest.mark.asyncio
async def test_invalidate_cached_object_permissions_broadcasts_to_other_workers():
    """Other workers hold their own in-memory copy, so eviction has to be broadcast, not just local."""
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
    from litellm.proxy.management_helpers.object_permission_utils import (
        invalidate_cached_object_permissions,
    )

    user_api_key_cache = UserApiKeyCache()
    user_api_key_cache.async_delete_cache = AsyncMock(side_effect=Exception("redis down"))

    with patch(
        "litellm.proxy.common_utils.auth_cache_invalidation_pubsub.publish_auth_cache_invalidation",
        new_callable=AsyncMock,
    ) as mock_publish:
        await invalidate_cached_object_permissions(
            object_permission_ids=("objperm-old", "objperm-old", None, 42, "objperm-new"),
            user_api_key_cache=user_api_key_cache,
        )

    assert [call.kwargs["cache_key"] for call in mock_publish.await_args_list] == [
        "object_permission_id:objperm-old",
        "object_permission_id:objperm-new",
    ]


@pytest.mark.asyncio
async def test_key_update_evicts_object_permission_before_key_object(monkeypatch):
    """The permission row must be evicted before the key object.

    ``get_key_object`` embeds the permission row in the cached key object, so a request landing
    between the two evictions would otherwise re-cache stale grants for a full key TTL.
    """
    from litellm.proxy._types import LiteLLM_ObjectPermissionBase
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache, object_permission_cache_key
    from litellm.proxy.utils import hash_token_if_needed

    deleted: list[str] = []

    class _RecordingCache(UserApiKeyCache):
        def delete_cache(self, key: str) -> None:
            deleted.append(key)
            super().delete_cache(key)

        async def async_delete_cache(self, key: str) -> None:
            deleted.append(key)
            await super().async_delete_cache(key)

    permission_id = "objperm-order"
    mock_prisma_client = AsyncMock()
    existing_permission_row = MagicMock()
    existing_permission_row.model_dump.return_value = {
        "object_permission_id": permission_id,
        "mcp_tool_permissions": {"server-1": ["tool_a"]},
    }
    mock_prisma_client.db.litellm_objectpermissiontable.find_unique = AsyncMock(
        return_value=existing_permission_row
    )
    mock_prisma_client.db.litellm_objectpermissiontable.upsert = AsyncMock(
        return_value=MagicMock(object_permission_id=permission_id)
    )
    existing_key_row = LiteLLM_VerificationToken(
        token="hashed-sk-lit5479",
        user_id="user-123",
        object_permission_id=permission_id,
    )
    mock_prisma_client.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing_key_row)
    updated_key = MagicMock()
    updated_key.model_dump.return_value = {"user_id": "user-123"}
    mock_prisma_client.update_data = AsyncMock(return_value={"data": updated_key})
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    with patch(
        "litellm.proxy.management_endpoints.key_management_endpoints.KeyManagementEventHooks.async_key_updated_hook"
    ):
        await _process_single_key_update(
            update_key_request=UpdateKeyRequest(
                key="sk-lit5479",
                object_permission=LiteLLM_ObjectPermissionBase(
                    mcp_tool_permissions={"server-1": ["tool_a", "tool_b"]}
                ),
            ),
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.PROXY_ADMIN,
                api_key="sk-admin",
                user_id="admin-user",
            ),
            litellm_changed_by=None,
            prisma_client=mock_prisma_client,
            user_api_key_cache=_RecordingCache(),
            proxy_logging_obj=AsyncMock(),
            llm_router=None,
            existing_key_row=existing_key_row,
        )

    assert deleted.index(object_permission_cache_key(permission_id)) < deleted.index(
        hash_token_if_needed("sk-lit5479")
    ), deleted


class TestTeamAdminMemberKeyBudgetUpdate:
    """LIT-5647: a team admin may update budget fields on another member's team key
    only when the proxy enables the 'member_key_budgets' permission."""

    def _member_key_row(self):
        return LiteLLM_VerificationToken(
            token="hashed_member_key",
            user_id="member-1",
            team_id="team-1",
            key_alias="member",
            models=["m"],
            max_budget=10.0,
            metadata={},
        )

    def _caller(self, user_id="team-admin-1"):
        return UserAPIKeyAuth(
            user_id=user_id,
            user_role=LitellmUserRoles.INTERNAL_USER,
        )

    def _team(self, members):
        return LiteLLM_TeamTableCachedObj(team_id="team-1", members_with_roles=members)

    def _setup(self, monkeypatch, team_obj, editable_fields):
        mock_get_team = AsyncMock(return_value=team_obj)
        monkeypatch.setattr(
            "litellm.proxy.management_endpoints.key_management_endpoints.get_team_object",
            mock_get_team,
        )
        monkeypatch.setattr(
            "litellm.proxy.management_helpers.team_member_permission_checks.get_team_object",
            mock_get_team,
        )
        monkeypatch.setattr(
            "litellm.proxy.proxy_server.general_settings",
            {"team_admin_editable_team_fields": editable_fields},
        )
        monkeypatch.setattr(
            "litellm.proxy.management_endpoints.key_management_endpoints.TeamMemberPermissionChecks",
            SimpleNamespace(
                can_team_member_execute_key_management_endpoint=AsyncMock(return_value=None),
                enforce_member_can_assign_access_groups=MagicMock(return_value=None),
            ),
        )
        monkeypatch.setattr(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_team_key_limits",
            AsyncMock(return_value=None),
        )

    @pytest.mark.asyncio
    async def test_team_admin_updates_member_key_budget_when_enabled(self, monkeypatch):
        self._setup(
            monkeypatch,
            self._team([Member(user_id="team-admin-1", role="admin"), Member(user_id="member-1", role="user")]),
            ["member_key_budgets"],
        )
        admin_check = AsyncMock(return_value=None)
        monkeypatch.setattr(
            "litellm.proxy.management_endpoints.key_management_endpoints._check_key_admin_access",
            admin_check,
        )
        await _validate_update_key_data(
            data=UpdateKeyRequest(key="sk-member", max_budget=0, budget_duration="30d"),
            existing_key_row=self._member_key_row(),
            user_api_key_dict=self._caller(),
            llm_router=None,
            premium_user=True,
            prisma_client=AsyncMock(),
            user_api_key_cache=MagicMock(),
        )
        admin_check.assert_called_once()

    @pytest.mark.asyncio
    async def test_team_admin_denied_when_permission_disabled(self, monkeypatch):
        self._setup(
            monkeypatch,
            self._team([Member(user_id="team-admin-1", role="admin"), Member(user_id="member-1", role="user")]),
            ["tpm_limit"],
        )
        with pytest.raises(HTTPException) as exc:
            await _validate_update_key_data(
                data=UpdateKeyRequest(key="sk-member", max_budget=0),
                existing_key_row=self._member_key_row(),
                user_api_key_dict=self._caller(),
                llm_router=None,
                premium_user=True,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        assert exc.value.status_code == 403
        assert "member_key_budgets" in str(exc.value.detail)
        assert "only create keys for themselves" not in str(exc.value.detail)

    @pytest.mark.asyncio
    async def test_enabled_but_non_budget_field_is_denied(self, monkeypatch):
        self._setup(
            monkeypatch,
            self._team([Member(user_id="team-admin-1", role="admin"), Member(user_id="member-1", role="user")]),
            ["member_key_budgets"],
        )
        with pytest.raises(HTTPException) as exc:
            await _validate_update_key_data(
                data=UpdateKeyRequest(key="sk-member", key_alias="renamed"),
                existing_key_row=self._member_key_row(),
                user_api_key_dict=self._caller(),
                llm_router=None,
                premium_user=True,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        assert exc.value.status_code == 403
        assert "'key_alias'" in str(exc.value.detail)

    @pytest.mark.asyncio
    async def test_ordinary_member_still_denied_on_another_members_key(self, monkeypatch):
        self._setup(
            monkeypatch,
            self._team([Member(user_id="member-2", role="user"), Member(user_id="member-1", role="user")]),
            ["member_key_budgets"],
        )
        with pytest.raises(HTTPException) as exc:
            await _validate_update_key_data(
                data=UpdateKeyRequest(key="sk-member", max_budget=0),
                existing_key_row=self._member_key_row(),
                user_api_key_dict=self._caller(user_id="member-2"),
                llm_router=None,
                premium_user=True,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        assert exc.value.status_code == 403
        assert "member_key_budgets" not in str(exc.value.detail)

    @pytest.mark.asyncio
    async def test_personal_key_owned_by_someone_else_still_denied(self, monkeypatch):
        self._setup(
            monkeypatch,
            self._team([Member(user_id="team-admin-1", role="admin")]),
            ["member_key_budgets"],
        )
        personal_row = LiteLLM_VerificationToken(
            token="hashed_personal",
            user_id="member-1",
            team_id=None,
            max_budget=10.0,
            metadata={},
        )
        with pytest.raises(HTTPException) as exc:
            await _validate_update_key_data(
                data=UpdateKeyRequest(key="sk-personal", max_budget=0),
                existing_key_row=personal_row,
                user_api_key_dict=self._caller(),
                llm_router=None,
                premium_user=True,
                prisma_client=AsyncMock(),
                user_api_key_cache=MagicMock(),
            )
        assert exc.value.status_code == 403
        assert "member_key_budgets" not in str(exc.value.detail)


_MEMBER_KEY_TEAM = LiteLLM_TeamTableCachedObj(
    team_id="team-1",
    members_with_roles=[
        Member(user_id="team-admin-1", role="admin"),
        Member(user_id="member-1", role="user"),
        Member(user_id="member-2", role="user"),
    ],
)


def test_team_admin_asking_for_a_teammates_team_key_is_a_member_key_request():
    assert _team_admin_requests_member_key(
        data=GenerateKeyRequest(user_id="member-1", team_id="team-1"),
        team_table=_MEMBER_KEY_TEAM,
        user_api_key_dict=UserAPIKeyAuth(user_id="team-admin-1", user_role=LitellmUserRoles.INTERNAL_USER),
    )


@pytest.mark.parametrize(
    "data, team_table, caller, caller_role",
    [
        pytest.param(
            GenerateKeyRequest(user_id="member-1", team_id="team-1"),
            _MEMBER_KEY_TEAM,
            "member-2",
            LitellmUserRoles.INTERNAL_USER,
            id="ordinary_member_for_another_member",
        ),
        pytest.param(
            GenerateKeyRequest(user_id="outsider", team_id="team-1"),
            _MEMBER_KEY_TEAM,
            "team-admin-1",
            LitellmUserRoles.INTERNAL_USER,
            id="team_admin_for_a_user_outside_the_team",
        ),
        pytest.param(
            GenerateKeyRequest(user_id="member-1"),
            None,
            "team-admin-1",
            LitellmUserRoles.INTERNAL_USER,
            id="personal_key_for_another_user",
        ),
        pytest.param(
            GenerateKeyRequest(user_id="team-admin-1", team_id="team-1"),
            _MEMBER_KEY_TEAM,
            "team-admin-1",
            LitellmUserRoles.INTERNAL_USER,
            id="team_admin_for_themselves",
        ),
        pytest.param(
            GenerateKeyRequest(team_id="team-1"),
            _MEMBER_KEY_TEAM,
            "team-admin-1",
            LitellmUserRoles.INTERNAL_USER,
            id="team_key_with_no_owner",
        ),
        pytest.param(
            GenerateKeyRequest(user_id="member-1", team_id="team-1"),
            _MEMBER_KEY_TEAM,
            "team-admin-1",
            LitellmUserRoles.PROXY_ADMIN,
            id="proxy_admin_keeps_the_proxy_admin_path",
        ),
    ],
)
def test_other_key_requests_are_not_member_key_requests(data, team_table, caller, caller_role):
    assert not _team_admin_requests_member_key(
        data=data,
        team_table=team_table,
        user_api_key_dict=UserAPIKeyAuth(user_id=caller, user_role=caller_role),
    )


@pytest.mark.parametrize("requested", [None, LiteLLMKeyType.DEFAULT, LiteLLMKeyType.LLM_API])
def test_a_member_key_is_always_saved_as_an_llm_api_key(requested):
    from litellm.proxy.management_endpoints.key_management_endpoints import handle_key_type

    request = _member_key_request(
        GenerateKeyRequest(user_id="member-1", team_id="team-1", key_type=requested), acting_as_team_admin=True
    )

    assert (request.user_id, request.team_id) == ("member-1", "team-1")
    assert handle_key_type(request, {}) == {"key_type": "llm_api", "allowed_routes": ["llm_api_routes"]}


def test_other_key_requests_keep_the_key_type_they_asked_for():
    from litellm.proxy.management_endpoints.key_management_endpoints import handle_key_type

    request = _member_key_request(GenerateKeyRequest(key_type=LiteLLMKeyType.MANAGEMENT), acting_as_team_admin=False)

    assert handle_key_type(request, {}) == {"key_type": "management", "allowed_routes": ["management_routes"]}


async def _team_admin_generates_member_key(
    find_owner: AsyncMock,
    generate_key: AsyncMock,
    editable_fields: tuple[str, ...] = ("create_member_keys",),
) -> GenerateKeyResponse:
    prisma_client: Final = MagicMock()
    prisma_client.writer_db.litellm_usertable.find_unique = find_owner
    with (
        patch("litellm.proxy.proxy_server.prisma_client", prisma_client),
        patch("litellm.proxy.proxy_server.llm_router", None),
        patch("litellm.proxy.proxy_server.premium_user", False),
        patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
        patch(
            "litellm.proxy.proxy_server.general_settings",
            {"team_admin_editable_team_fields": list(editable_fields)},
        ),
        patch(
            "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn",
            generate_key,
        ),
    ):
        return await _common_key_generation_helper(
            data=GenerateKeyRequest(user_id="member-1", team_id="team-1"),
            user_api_key_dict=UserAPIKeyAuth(user_id="team-admin-1", user_role=LitellmUserRoles.INTERNAL_USER),
            litellm_changed_by=None,
            team_table=_MEMBER_KEY_TEAM,
        )


@pytest.mark.asyncio
async def test_team_admin_creates_an_llm_api_key_owned_by_an_internal_user_teammate():
    generate_key: Final = AsyncMock(return_value={"key": "sk-member", "user_id": "member-1", "team_id": "team-1"})

    await _team_admin_generates_member_key(
        AsyncMock(return_value=MagicMock(user_role=LitellmUserRoles.INTERNAL_USER.value)), generate_key
    )

    saved: Final = generate_key.await_args.kwargs
    assert (saved["user_id"], saved["team_id"]) == ("member-1", "team-1")
    assert (saved["key_type"], saved["allowed_routes"]) == ("llm_api", ["llm_api_routes"])


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "default_key_generate_params",
    [None, {"allowed_routes": ["/chat/completions"]}],
    ids=["default_off", "default_without_llm_api_routes"],
)
async def test_custom_key_policy_sees_the_routes_a_member_key_is_saved_with(
    monkeypatch: pytest.MonkeyPatch, default_key_generate_params: dict[str, list[str]] | None
) -> None:
    monkeypatch.setattr(litellm, "default_key_generate_params", default_key_generate_params)
    policy: Final = AsyncMock(return_value={"decision": True})
    generate_key: Final = AsyncMock(return_value={"key": "sk-member", "user_id": "member-1", "team_id": "team-1"})

    with patch("litellm.proxy.proxy_server.user_custom_key_policy", policy):  # test-quality-ok: inject policy hook
        await _team_admin_generates_member_key(
            AsyncMock(return_value=MagicMock(user_role=LitellmUserRoles.INTERNAL_USER.value)), generate_key
        )

    policy_request: Final = policy.await_args.args[0]
    assert policy_request.effective_key.allowed_routes == ["llm_api_routes"]
    assert policy_request.effective_key.allowed_routes == generate_key.await_args.kwargs["allowed_routes"]


@pytest.mark.asyncio
async def test_team_admin_cannot_create_a_key_owned_by_a_proxy_admin_teammate():
    generate_key: Final = AsyncMock()

    with pytest.raises(HTTPException) as exc:
        await _team_admin_generates_member_key(
            AsyncMock(return_value=MagicMock(user_role=LitellmUserRoles.PROXY_ADMIN.value)), generate_key
        )

    assert exc.value.status_code == 403
    generate_key.assert_not_awaited()


@pytest.mark.asyncio
async def test_member_key_request_with_the_setting_off_is_refused_without_reading_the_owner():
    find_owner: Final = AsyncMock(side_effect=ConnectionError("db down"))

    with pytest.raises(HTTPException) as exc:
        await _team_admin_generates_member_key(find_owner, AsyncMock(), editable_fields=())

    assert exc.value.status_code == 403
    find_owner.assert_not_awaited()


@pytest.mark.asyncio
async def test_rotate_master_key_reencrypts_guardrail_params(monkeypatch):
    import json
    from types import SimpleNamespace
    from unittest.mock import AsyncMock, MagicMock

    from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
    from litellm.proxy.guardrails.guardrail_registry import (
        decrypt_guardrail_litellm_params,
        encrypt_guardrail_litellm_params,
    )
    from litellm.proxy.management_endpoints import key_management_endpoints
    from litellm.proxy.management_endpoints.key_management_endpoints import (
        rotate_master_key,
    )

    for rotator in (
        "rotate_mcp_server_credentials_master_key",
        "rotate_mcp_user_credentials_master_key",
        "rotate_mcp_user_env_vars_master_key",
        "rotate_sso_identity_assertions_master_key",
    ):
        monkeypatch.setattr(key_management_endpoints, rotator, AsyncMock())
    monkeypatch.delenv("LITELLM_SALT_KEY", raising=False)
    monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-old-master-key")
    guardrail_row = SimpleNamespace(
        guardrail_id="g-1",
        updated_at="t1",
        litellm_params=encrypt_guardrail_litellm_params({"guardrail": "bedrock", "aws_secret_access_key": "aws-secret"}),
    )
    mock_prisma_client = AsyncMock()
    mock_prisma_client.db = MagicMock()
    mock_prisma_client.db.litellm_proxymodeltable.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_config.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_credentialstable.find_many = AsyncMock(return_value=[])
    mock_prisma_client.db.litellm_guardrailstable.find_many = AsyncMock(return_value=[guardrail_row])
    mock_prisma_client.db.litellm_guardrailstable.update_many = AsyncMock(return_value=1)

    await rotate_master_key(
        prisma_client=mock_prisma_client,
        user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="test-user"),
        current_master_key="sk-old-master-key",
        new_master_key="sk-new-master-key",
    )

    write = mock_prisma_client.db.litellm_guardrailstable.update_many.call_args.kwargs
    stored_params = json.loads(write["data"]["litellm_params"])
    monkeypatch.setattr("litellm.proxy.proxy_server.master_key", "sk-new-master-key")
    assert write["where"] == {"guardrail_id": "g-1", "updated_at": "t1"}
    assert stored_params["aws_secret_access_key"].startswith("litellm_enc::")
    assert decrypt_guardrail_litellm_params(stored_params) == {
        "guardrail": "bedrock",
        "aws_secret_access_key": "aws-secret",
    }


def test_is_team_key() -> None:
    assert _is_team_key(GenerateKeyRequest(team_id="test_team_id"))
    assert not _is_team_key(GenerateKeyRequest(user_id="test_user_id"))


def test_team_key_generation_team_member_check(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        litellm,
        "key_generation_settings",
        {"team_key_generation": {"allowed_team_member_roles": ["admin"]}},
        raising=False,
    )
    team: Final = LiteLLM_TeamTableCachedObj(
        team_id="test_team_id",
        team_alias="test_team_alias",
        members_with_roles=[Member(role="admin", user_id="test_user_id")],
    )
    admin_member: Final = UserAPIKeyAuth(
        user_id="test_user_id",
        user_role=LitellmUserRoles.INTERNAL_USER,
        api_key="sk-test",
        team_member=Member(role="admin", user_id="test_user_id"),
    )
    assert _team_key_generation_check(
        team_table=team,
        user_api_key_dict=admin_member,
        data=GenerateKeyRequest(),
        route=KeyManagementRoutes.KEY_GENERATE,
    )
    user_team: Final = team.model_copy(
        update={"members_with_roles": [Member(role="user", user_id="test_user_id")]}
    )
    user_member: Final = admin_member.model_copy(
        update={"team_member": Member(role="user", user_id="test_user_id")}
    )
    with pytest.raises(HTTPException):
        _team_key_generation_check(
            team_table=user_team,
            user_api_key_dict=user_member,
            data=GenerateKeyRequest(),
            route=KeyManagementRoutes.KEY_GENERATE,
        )


def test_key_generation_required_params_check() -> None:
    assert _key_generation_required_param_check(
        GenerateKeyRequest(tags=["test_tags"]),
        ["tags"],
    )
    assert _key_generation_required_param_check(GenerateKeyRequest(), None)
    with pytest.raises(HTTPException, match="Required param models"):
        _key_generation_required_param_check(
            GenerateKeyRequest(tags=["test_tags"]),
            ["models"],
        )


def test_personal_key_generation_check(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        litellm,
        "key_generation_settings",
        {"personal_key_generation": {"allowed_user_roles": ["proxy_admin"]}},
        raising=False,
    )
    assert _personal_key_generation_check(
        user_api_key_dict=UserAPIKeyAuth(
            user_role=LitellmUserRoles.PROXY_ADMIN,
            api_key="sk-test",
            user_id="admin",
        ),
        data=GenerateKeyRequest(),
    )
    with pytest.raises(HTTPException):
        _personal_key_generation_check(
            user_api_key_dict=UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER,
                api_key="sk-test",
                user_id="admin",
            ),
            data=GenerateKeyRequest(),
        )


def test_prepare_metadata_fields(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    cases: Final[tuple[tuple[UpdateKeyRequest, dict[str, JsonValue], dict[str, JsonValue], dict[str, JsonValue]], ...]] = (
        (
            UpdateKeyRequest(key="sk-test", metadata={"test": "new"}),
            {"metadata": {"test": "new"}},
            {"test": "test"},
            {"metadata": {"test": "new"}},
        ),
        (
            UpdateKeyRequest(key="sk-test", tags=["new_tag"]),
            {},
            {"tags": ["old_tag"]},
            {"metadata": {"tags": ["new_tag"]}},
        ),
        (
            UpdateKeyRequest(key="sk-test", enforced_params=["metadata.tags"]),
            {},
            {"tags": ["old_tag"]},
            {"metadata": {"tags": ["old_tag"], "enforced_params": ["metadata.tags"]}},
        ),
        (
            UpdateKeyRequest(key="sk-test", disable_global_guardrails=True),
            {},
            {},
            {"metadata": {"disable_global_guardrails": True}},
        ),
        (
            UpdateKeyRequest(key="sk-test", disable_global_guardrails=False),
            {},
            {"disable_global_guardrails": True},
            {"metadata": {"disable_global_guardrails": False}},
        ),
    )
    for data, non_default_values, existing_metadata, expected in cases:
        assert prepare_metadata_fields(
            data=data,
            non_default_values=non_default_values,
            existing_metadata=existing_metadata,
        ) == expected


@pytest.mark.asyncio
async def test_key_generate_reads_the_team_from_the_writer_database_not_the_cache(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy import proxy_server

    cache: Final = UserApiKeyCache()
    cached_team: Final = LiteLLM_TeamTableCachedObj(team_id="1234", team_alias="cached-team")
    await cache.async_set_cache(key="team_id:1234", value=cached_team, model_type=LiteLLM_TeamTableCachedObj, ttl=60)
    prisma_client: Final = MagicMock()
    prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=cached_team)
    prisma_client.writer_db.litellm_teamtable.find_unique = AsyncMock(return_value=None)
    monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
    monkeypatch.setattr(proxy_server, "user_api_key_cache", cache)

    with pytest.raises(ProxyException) as raised:
        await generate_key_fn(
            data=GenerateKeyRequest(team_id="1234"),
            user_api_key_dict=UserAPIKeyAuth(
                api_key="sk-integration-test",
                user_id="user",
                user_role=LitellmUserRoles.INTERNAL_USER,
            ),
        )

    assert raised.value.message == "Team not found for team_id=1234. Non-admin users cannot create keys for non-existent teams."


def test_key_info_unexpected_database_exception_sanitized(
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
) -> None:
    from litellm.proxy import proxy_server
    from litellm.proxy.auth.user_api_key_auth import user_api_key_auth

    mock_prisma: Final = MagicMock()
    secret_marker: Final = "SECRET_DB_DETAIL: invalid database statement"
    mock_prisma.db.litellm_verificationtoken.find_unique = AsyncMock(
        side_effect=RuntimeError(secret_marker)
    )
    monkeypatch.setattr(proxy_server, "prisma_client", mock_prisma)

    admin_auth: Final = UserAPIKeyAuth(
        api_key="sk-test-master",
        user_role=LitellmUserRoles.PROXY_ADMIN,
    )
    proxy_server.app.dependency_overrides[user_api_key_auth] = lambda: admin_auth

    try:
        client: Final = TestClient(proxy_server.app)
        with caplog.at_level("ERROR"):
            response: Final = client.get("/key/info?key=sk-target")
        assert response.status_code == 500
        assert secret_marker not in response.text
        assert response.json()["error"]["message"] == "Internal server error from /key/info. Details are in the proxy server logs."
        assert secret_marker in caplog.text
    finally:
        proxy_server.app.dependency_overrides.pop(user_api_key_auth, None)


def test_key_info_missing_key_preserves_404(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy import proxy_server
    from litellm.proxy.auth.user_api_key_auth import user_api_key_auth

    mock_prisma: Final = MagicMock()
    mock_prisma.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=None)
    mock_prisma.db.litellm_deletedverificationtoken.find_first = AsyncMock(return_value=None)
    monkeypatch.setattr(proxy_server, "prisma_client", mock_prisma)

    admin_auth: Final = UserAPIKeyAuth(
        api_key="sk-test-master",
        user_role=LitellmUserRoles.PROXY_ADMIN,
    )
    proxy_server.app.dependency_overrides[user_api_key_auth] = lambda: admin_auth

    try:
        client: Final = TestClient(proxy_server.app)
        response: Final = client.get("/key/info?key=sk-nonexistent")
        assert response.status_code == 404
        assert response.json()["error"]["message"] == "Key not found in database"
    finally:
        proxy_server.app.dependency_overrides.pop(user_api_key_auth, None)


def test_key_info_permission_denied_preserves_403(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from litellm.proxy import proxy_server
    from litellm.proxy.auth.user_api_key_auth import user_api_key_auth

    mock_key: Final = MagicMock()
    mock_key.token = "hashed-other-token"
    mock_key.user_id = "other-user"
    mock_key.model_dump.return_value = {
        "token": "hashed-other-token",
        "user_id": "other-user",
        "team_id": None,
        "blocked": False,
        "expires": None,
    }
    mock_prisma: Final = MagicMock()
    mock_prisma.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=mock_key)
    monkeypatch.setattr(proxy_server, "prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.management_endpoints.key_management_endpoints._can_user_query_key_info",
        AsyncMock(return_value=False),
    )

    user_auth: Final = UserAPIKeyAuth(
        api_key="sk-regular-user",
        user_id="user1",
        user_role=LitellmUserRoles.INTERNAL_USER,
    )
    proxy_server.app.dependency_overrides[user_api_key_auth] = lambda: user_auth

    try:
        client: Final = TestClient(proxy_server.app)
        response: Final = client.get("/key/info?key=sk-other-key")
        assert response.status_code == 403
        assert "not allowed to access this key's info" in response.text
    finally:
        proxy_server.app.dependency_overrides.pop(user_api_key_auth, None)


def test_key_info_database_not_connected_sanitized_500(
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
) -> None:
    from litellm.proxy import proxy_server
    from litellm.proxy.auth.user_api_key_auth import user_api_key_auth

    monkeypatch.setattr(proxy_server, "prisma_client", None)

    admin_auth: Final = UserAPIKeyAuth(
        api_key="sk-test-master",
        user_role=LitellmUserRoles.PROXY_ADMIN,
    )
    proxy_server.app.dependency_overrides[user_api_key_auth] = lambda: admin_auth

    try:
        client: Final = TestClient(proxy_server.app)
        with caplog.at_level("ERROR"):
            response: Final = client.get("/key/info?key=sk-target")
        assert response.status_code == 500
        assert response.json()["error"]["message"] == "Internal server error from /key/info. Details are in the proxy server logs."
        assert "Database not connected" in caplog.text
    finally:
        proxy_server.app.dependency_overrides.pop(user_api_key_auth, None)