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]

return detailed error message on check_valid_ip

Ishaan Jaffe0978378c13f
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index 9bbbc1a430f..7ed45bb51a6 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -12,7 +12,7 @@ import json
import secrets
import traceback
from datetime import datetime, timedelta, timezone
-from typing import Optional
+from typing import Optional, Tuple
from uuid import uuid4
import fastapi
@@ -123,7 +123,7 @@ async def user_api_key_auth(
# Check 2. FILTER IP ADDRESS
await check_if_request_size_is_safe(request=request)
- is_valid_ip = _check_valid_ip(
+ is_valid_ip, passed_in_ip = _check_valid_ip(
allowed_ips=general_settings.get("allowed_ips", None),
use_x_forwarded_for=general_settings.get("use_x_forwarded_for", False),
request=request,
@@ -132,7 +132,7 @@ async def user_api_key_auth(
if not is_valid_ip:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
- detail="Access forbidden: IP address not allowed.",
+ detail=f"Access forbidden: IP address {passed_in_ip} not allowed.",
)
pass_through_endpoints: Optional[List[dict]] = general_settings.get(
@@ -1212,12 +1212,12 @@ def _check_valid_ip(
allowed_ips: Optional[List[str]],
request: Request,
use_x_forwarded_for: Optional[bool] = False,
-) -> bool:
+) -> Tuple[bool, Optional[str]]:
"""
Returns if ip is allowed or not
"""
if allowed_ips is None: # if not set, assume true
- return True
+ return True, None
# if general_settings.get("use_x_forwarded_for") is True then use x-forwarded-for
client_ip = None
@@ -1228,9 +1228,9 @@ def _check_valid_ip(
# Check if IP address is allowed
if client_ip not in allowed_ips:
- return False
+ return False, client_ip
- return True
+ return True, client_ip
def get_api_key_from_custom_header(
diff --git a/litellm/tests/test_user_api_key_auth.py b/litellm/tests/test_user_api_key_auth.py
index ad057ee5725..e0595ac13c7 100644
--- a/litellm/tests/test_user_api_key_auth.py
+++ b/litellm/tests/test_user_api_key_auth.py
@@ -44,7 +44,7 @@ def test_check_valid_ip(
request = Request(client_ip)
- assert _check_valid_ip(allowed_ips, request) == expected_result # type: ignore
+ assert _check_valid_ip(allowed_ips, request)[0] == expected_result # type: ignore
# test x-forwarder for is used when user has opted in
@@ -72,7 +72,7 @@ def test_check_valid_ip_sent_with_x_forwarded_for(
request = Request(client_ip, headers={"X-Forwarded-For": client_ip})
- assert _check_valid_ip(allowed_ips, request, use_x_forwarded_for=True) == expected_result # type: ignore
+ assert _check_valid_ip(allowed_ips, request, use_x_forwarded_for=True)[0] == expected_result # type: ignore
@pytest.mark.asyncio