Skip to content
Closed
35 changes: 0 additions & 35 deletions litellm/proxy/auth/auth_checks.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't this a regression for jwt auth?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@greptile can you confirm this?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on my analysis of the diff, yes — this is a regression for JWT auth.

Here's why:

Before: _check_end_user_budget was called directly inside get_end_user_object, which is invoked from both the key auth path AND the JWT auth path (handle_jwt.py also calls get_end_user_object). Budget enforcement was guaranteed regardless of auth method.

After: The budget check was removed from get_end_user_object and moved to two places in user_api_key_auth.py:

  1. Check 5c in _user_api_key_auth_builder (key auth path)
  2. Check 4b in _run_post_custom_auth_checks (custom auth)

The new Check 5c only fires if valid_token.end_user_max_budget is not None. This field is populated via update_valid_token_with_end_user_params. For the JWT auth path, the end_user_params dict is constructed from the JWT builder result — and there's no evidence in this PR that end_user_max_budget is being populated in that flow. If it's None on the token (the default), the check is silently skipped.

The net result: a JWT-authenticated end user who has exceeded their max_budget will no longer be blocked, because:

  1. get_end_user_object no longer raises BudgetExceededError
  2. Check 5c won't trigger if valid_token.end_user_max_budget was never set from the JWT path

Can you confirm whether end_user_max_budget is reliably populated on valid_token during JWT auth? If not, you'll need to either ensure the JWT builder populates it, or add a fallback in Check 5c that reads _end_user_object.litellm_budget_table.max_budget directly when valid_token.end_user_max_budget is None.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules and .greptile/config.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@greptile does adding a simple fallback like:
if end_user_mb is None and end_user_object is not None:
end_user_mb = getattr(end_user_object.litellm_budget_table, 'max_budget', None)
in 5c and 4b solves the issue?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the fallback is the right approach, but your proposed code has a subtle bug: getattr(end_user_object.litellm_budget_table, 'max_budget', None) will raise AttributeError if litellm_budget_table itself is None — the getattr default only catches missing attributes, not None.attr access.

The safe version:

end_user_mb = valid_token.end_user_max_budget
if end_user_mb is None and _end_user_object is not None:
    budget_table = _end_user_object.litellm_budget_table
    end_user_mb = budget_table.max_budget if budget_table is not None else None

Apply this before the existing if end_user_mb is not None check in both 5c and 4b (using end_user_object instead of _end_user_object in 4b, since that's the variable name there).

This ensures:

  1. JWT auth path: even if valid_token.end_user_max_budget was never populated from end_user_params, the budget is read directly from the fetched end_user_object
  2. Key auth path: no change in behavior since valid_token.end_user_max_budget is already populated via update_valid_token_with_end_user_params
  3. No None pointer risk from a missing litellm_budget_table

Tip: You can customize Greptile's behavior for this repo with .greptile/rules and .greptile/config.

Original file line number Diff line number Diff line change
Expand Up @@ -866,35 +866,6 @@ async def _apply_default_budget_to_end_user(
return end_user_obj


def _check_end_user_budget(
end_user_obj: LiteLLM_EndUserTable,
route: str,
) -> None:
"""
Check if end user is within their budget limit.

Args:
end_user_obj: The end user object to check
route: The request route

Raises:
litellm.BudgetExceededError: If end user has exceeded their budget
"""
if RouteChecks.is_info_route(route):
return

if end_user_obj.litellm_budget_table is None:
return

end_user_budget = end_user_obj.litellm_budget_table.max_budget
if end_user_budget is not None and end_user_obj.spend > end_user_budget:
raise litellm.BudgetExceededError(
current_cost=end_user_obj.spend,
max_budget=end_user_budget,
message=f"ExceededBudget: End User={end_user_obj.user_id} over budget. Spend={end_user_obj.spend}, Budget={end_user_budget}",
)


@log_db_metrics
async def get_end_user_object(
end_user_id: Optional[str],
Expand Down Expand Up @@ -942,9 +913,6 @@ async def get_end_user_object(
parent_otel_span=parent_otel_span,
)

# Check budget limits
_check_end_user_budget(end_user_obj=return_obj, route=route)

return return_obj

# Fetch from database
Expand Down Expand Up @@ -973,9 +941,6 @@ async def get_end_user_object(
key="end_user_id:{}".format(end_user_id), value=_response.dict()
)

# Check budget limits
_check_end_user_budget(end_user_obj=_response, route=route)

return _response

except Exception as e:
Expand Down
30 changes: 30 additions & 0 deletions litellm/proxy/auth/user_api_key_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,8 @@ def update_valid_token_with_end_user_params(
valid_token.end_user_model_max_budget = end_user_params[
"end_user_model_max_budget"
]
if end_user_params.get("end_user_max_budget") is not None:
valid_token.end_user_max_budget = end_user_params["end_user_max_budget"]
return valid_token


Expand Down Expand Up @@ -1428,6 +1430,20 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
model=current_model,
)

# Check 5c. End user max budget
end_user_mb = valid_token.end_user_max_budget
if (
end_user_mb is not None
and _end_user_object is not None
and valid_token.end_user_id is not None
):
await proxy_logging_obj.max_budget_limiter.is_end_user_within_budget(
end_user_id=valid_token.end_user_id,
end_user_max_budget=end_user_mb,
end_user_spend=_end_user_object.spend,
route=route,
)
Comment on lines +1483 to +1499

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Redundant check with common_checks

common_checks (called a few lines later at line 1519) already performs the identical end-user budget comparison using end_user_object.litellm_budget_table.max_budget, and it is also inside if not skip_budget_checks:. "Check 5c" will always agree with the common_checks result, so this block fires twice on every non-zero-cost request. It isn't harmful, but it adds noise and a second potential raise path. Consider removing "Check 5c" and letting common_checks remain the single source of truth for this check in the key-auth flow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@greptile There were already duplication in Team Budget Checks and Global Proxy Budget Check between common_checks and the logic inside user_api_key_auth.py. This is a job for another refactor.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point — if Team and Global Proxy budget checks already follow the same "duplicated in both places" pattern, then this PR is consistent with the existing style rather than introducing a new problem. The broader deduplication is a separate concern.

Tip: You can give me more context with .greptile/rules so I get this right next time.


# Check 6: Additional Common Checks across jwt + key auth
if valid_token.team_id is not None:
try:
Expand Down Expand Up @@ -1935,6 +1951,20 @@ async def _run_post_custom_auth_checks(
model=current_model,
)

# 4b. Check end-user max_budget
end_user_mb = valid_token.end_user_max_budget
if (
end_user_mb is not None
and end_user_object is not None
and valid_token.end_user_id is not None
):
await proxy_logging_obj.max_budget_limiter.is_end_user_within_budget(
end_user_id=valid_token.end_user_id,
end_user_max_budget=end_user_mb,
end_user_spend=end_user_object.spend,
route=route,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Zero-cost bypass missing in custom-auth path

In the standard key-auth and JWT auth flows, "Check 5c" and the common_checks end-user budget check both sit inside if not skip_budget_checks:, so zero-cost models skip them correctly. However, _run_post_custom_auth_checks never evaluates _is_model_cost_zero or sets skip_budget_checks, so "4b" here will block over-budget end-users even when the requested model is free. The same gap exists for the existing model_max_budget check at line 1923, but this new check makes the asymmetry more visible. Consider computing skip_budget_checks at the start of _run_post_custom_auth_checks (same logic as lines 1283-1295) and guarding both "4b" and the model-budget check with it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@greptile Is the problem now fixed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the issue is now fixed. The PR adds exactly the guard I described:

# 2a. Check if model has zero cost - if so, skip all budget checks
model = get_model_from_request(request_data, route)
skip_budget_checks = False
if model is not None and llm_router is not None:
    skip_budget_checks = _is_model_cost_zero(model=model, llm_router=llm_router)

All three budget checks in _run_post_custom_auth_checks — key model budget (check 3), end-user model budget (check 4), and end-user max budget (check 4b) — are now wrapped under if not skip_budget_checks:. The flag is also forwarded into common_checks at the bottom of the function, so zero-cost models correctly bypass all budget enforcement in the custom-auth path.


# 5. Look up user object if user_id is set
user_object = None
if valid_token.user_id is not None:
Expand Down
28 changes: 28 additions & 0 deletions litellm/proxy/hooks/max_budget_limiter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from fastapi import HTTPException

import litellm
from litellm import verbose_logger
from litellm._logging import verbose_proxy_logger
from litellm.caching.caching import DualCache
Expand All @@ -12,6 +13,33 @@
def __init__(self):
pass

async def is_end_user_within_budget(
self,
end_user_id: str,
end_user_max_budget: float,
end_user_spend: float,
route: str,
) -> bool:
"""
Check if an end-user is within their overall max budget.

Raises:
BudgetExceededError: If the end-user has exceeded overall budget.
"""
from litellm.proxy.auth.route_checks import RouteChecks

if RouteChecks.is_info_route(route):
return True

if end_user_spend > end_user_max_budget:
raise litellm.BudgetExceededError(
current_cost=end_user_spend,
max_budget=end_user_max_budget,
message=f"ExceededBudget: End User={end_user_id} over budget. Spend={end_user_spend}, Budget={end_user_max_budget}",
)

return True

async def async_pre_call_hook(
self,
user_api_key_dict: UserAPIKeyAuth,
Expand Down
2 changes: 2 additions & 0 deletions litellm/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -7754,6 +7754,8 @@ def get_deployment_model_info(
)
elif litellm_model_name_model_info is not None:
model_info = litellm_model_name_model_info
elif custom_model_info is not None:
model_info = cast(ModelInfo, custom_model_info)

return model_info

Expand Down
40 changes: 14 additions & 26 deletions tests/proxy_unit_tests/test_auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
async def test_get_end_user_object(customer_spend, customer_budget):
"""
Scenario 1: normal
Scenario 2: user over budget
Scenario 2: user over budget (should still return object here, as the budget check happens in max_budget_limiter)
"""
end_user_id = "my-test-customer"
_budget = LiteLLM_BudgetTable(max_budget=customer_budget)
Expand All @@ -51,31 +51,19 @@ async def test_get_end_user_object(customer_spend, customer_budget):
_cache = DualCache()
_key = "end_user_id:{}".format(end_user_id)
_cache.set_cache(key=_key, value=end_user_obj.model_dump())
try:
await get_end_user_object(
end_user_id=end_user_id,
prisma_client="RANDOM VALUE", # type: ignore
user_api_key_cache=_cache,
route="/v1/chat/completions",
)
if customer_spend > customer_budget:
pytest.fail(
"Expected call to fail. Customer Spend={}, Customer Budget={}".format(
customer_spend, customer_budget
)
)
except Exception as e:
if (
isinstance(e, litellm.BudgetExceededError)
and customer_spend > customer_budget
):
pass
else:
pytest.fail(
"Expected call to work. Customer Spend={}, Customer Budget={}, Error={}".format(
customer_spend, customer_budget, str(e)
)
)

result = await get_end_user_object(
end_user_id=end_user_id,
prisma_client="RANDOM VALUE", # type: ignore
user_api_key_cache=_cache,
route="/v1/chat/completions",
)

assert result is not None
assert result.user_id == end_user_id
assert result.spend == customer_spend
assert result.litellm_budget_table is not None
assert result.litellm_budget_table.max_budget == customer_budget


@pytest.mark.parametrize(
Expand Down
22 changes: 17 additions & 5 deletions tests/proxy_unit_tests/test_default_end_user_budget_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,25 @@ async def test_budget_enforcement_blocks_over_budget_users():
mock_cache.async_get_cache = AsyncMock(return_value=None)
mock_cache.async_set_cache = AsyncMock()

# Should raise BudgetExceededError
# 1. Fetch the user object (this no longer throws an exception)
result = await get_end_user_object(
end_user_id=end_user_id,
prisma_client=mock_prisma_client,
user_api_key_cache=mock_cache,
route="/chat/completions",
)

from litellm.proxy.hooks.max_budget_limiter import _PROXY_MaxBudgetLimiter
budget_limiter = _PROXY_MaxBudgetLimiter()
assert default_budget.max_budget is not None

# 2. Check that the new limiter function correctly enforces the budget using the mocked values
with pytest.raises(litellm.BudgetExceededError) as exc_info:
await get_end_user_object(
await budget_limiter.is_end_user_within_budget(
end_user_id=end_user_id,
prisma_client=mock_prisma_client,
user_api_key_cache=mock_cache,
route="/chat/completions",
end_user_max_budget=default_budget.max_budget,
end_user_spend=mock_end_user_data["spend"],
route="/chat/completions"
)

assert "ExceededBudget" in str(exc_info.value)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_litellm/test_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -1955,6 +1955,25 @@ def mock_get_model_info_side_effect(model):
# Should return None when no model info is found
assert result is None

# Test Case 6: Only custom model info exists (no model-name info)
mock_custom_only_info = {
"input_cost_per_token": 0.0,
"output_cost_per_token": 0.0,
"mode": "chat",
"litellm_provider": "openai",
}

with patch.object(litellm, "model_cost", {"custom-only-id": mock_custom_only_info}):
with patch.object(litellm, "get_model_info", return_value=None):
result = router.get_deployment_model_info(
model_id="custom-only-id", model_name="missing-model-name"
)

assert result is not None
assert result["input_cost_per_token"] == 0.0
assert result["output_cost_per_token"] == 0.0
assert result["litellm_provider"] == "openai"

print("✓ All base model flow test cases passed!")


Expand Down
Loading