mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-25 22:20:43 +00:00
* test(auth): use the production cache in auth fixtures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(gateway): serve one native app in both modes, answering a master key caller's /v1/messages with it in front of Python (#52229) Forwarding mode forwarded everything to Python with no native app behind it, and standalone mode built its own, so the two modes could not share a layer. The gateway now builds one native app in main.rs and serves it in both modes. Standalone serves it on its own listener. In front of Python, gateway-forward takes it as any tower Service together with `admit`, never as an axum Router, and composes the two itself, so no request Python answers passes through a native layer. `admit` is the only thing that decides who answers, and x-litellm-gateway names who did. `admit` is a value built from the config and called per request. It judges a request by its route, POST /v1/messages, and its caller, the master key. One that passes is answered by the native app, and Python never sees it. This is the happy path only. The config's settings and the request's headers and body are not judged yet, so a setting or parameter only Python honors is served natively until a later change adds those judges. A gateway that loaded no config refuses every request with reason configuration. x-litellm-gateway now names which check refused, as configuration, route or credential. In front of Python the native app is built from the config file Python runs with. The supervisor resolves the local YAML file by Python's own precedence, which is CONFIG_FILE_PATH, else --config, and none when LITELLM_CONFIG_BUCKET_NAME moves the config to a bucket. It passes the path as LITELLM_FORWARD_CONFIG, and the gateway loads it the way standalone mode does. With no local file the config is empty. A file the gateway cannot load, or a config the native app cannot be built from, is logged as an error and also leaves the config empty with every request refused, because the gateway exiting would stop Python with it. Config stored in the database is not read yet. Forwarding mode now builds the same AppState and verifies the same license as standalone. The new process module reads the environment once and picks the mode, replacing settings.rs. NON_LLM_CONNECTION_TIMEOUT is read the way Python's get_env_int reads it, so a blank or unparsable value no longer stops the gateway, and Python with it, in forwarding mode. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> * feat(proxy)!: let every key read its own spend logs and return 403 for filters outside the caller's scope (#52449) * feat(proxy): let a key read its own rows on /spend/logs and /spend/logs/v2 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(proxy): refuse internal users' foreign spend-log filters and let route-restricted keys read their own spend logs Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(proxy): keep org admins' spend-log scope, hold impersonation to the key's allowed_routes and keep deleted keys' history readable Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): type the new spend-log test parameters Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(proxy): keep the spend-log checks inside the type gate Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): cover a role-less key reading its own spend logs in unit tests Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(proxy): cover missing spend log key identities and deleted keys Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * refactor(proxy): return spend log filter denials as values Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(auth): use the production cache in auth fixtures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(auth): reuse the proxy cache export in fixtures Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: mateo <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: yujonglee <yujong@berri.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Kerry Lu <kerry@berri.ai>
167 lines
8.2 KiB
Python
167 lines
8.2 KiB
Python
import asyncio
|
|
from collections.abc import Awaitable, Mapping
|
|
from types import MappingProxyType
|
|
from typing import Final, Literal
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, Request
|
|
from pydantic import TypeAdapter
|
|
|
|
import litellm
|
|
from litellm.exceptions import BadRequestError
|
|
from litellm.litellm_core_utils.initialize_dynamic_callback_params import inherit_message_logging_privacy
|
|
from litellm.litellm_core_utils.litellm_logging import Logging
|
|
from litellm.litellm_core_utils.redact_messages import should_redact_message_logging
|
|
from litellm.proxy import common_request_processing, proxy_server
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from litellm.proxy.auth.auth_checks import can_key_call_model
|
|
from litellm.proxy.proxy_server import UserApiKeyCache
|
|
from litellm.proxy._types import ProxyException
|
|
from litellm.proxy.hooks.parallel_request_limiter_v3 import get_or_create_request_stash, get_request_stash
|
|
from litellm.proxy.native_compaction import with_proxy_compaction_executor
|
|
from litellm.router import Router
|
|
from litellm.router_strategy.complexity_router.context_compaction import compaction_executor, reject_recursive_compactor
|
|
from litellm.types.utils import ModelResponse
|
|
from tests.unit.proxy._prisma import prisma_with_empty_config
|
|
|
|
_HEADERS: Final = (
|
|
(b"authorization", b"Bearer sk-compaction-fixture"), (b"cookie", b"session=fixture"),
|
|
(b"content-length", b"99999"), (b"x-litellm-call-id", b"parent"),
|
|
(b"litellm-disable-message-redaction", b"true"), (b"x-litellm-num-retries", b"8"),
|
|
(b"X-LiteLLM-Timeout", b"600"), (b"x-litellm-stream-timeout", b"500"),
|
|
)
|
|
|
|
|
|
async def _child(
|
|
protocol: Literal["chat", "messages"] = "chat", forged: bool = False, parent_model: str | None = None
|
|
) -> Mapping[str, object]:
|
|
executor: Final = compaction_executor.get()
|
|
assert executor is not None
|
|
payload: Final = TypeAdapter(Mapping[str, object]).validate_json(
|
|
b'{"model":"compactor","messages":[{"role":"user","content":"history"}],'
|
|
b'"num_retries":0,"timeout":7,"stream_timeout":7,"disable_fallbacks":true,"stream":false,'
|
|
b'"metadata":{"turn_off_message_logging":true}}'
|
|
)
|
|
return await executor(protocol, MappingProxyType({
|
|
"litellm_metadata" if protocol == "messages" and key == "metadata" else key: value
|
|
for key, value in payload.items() if forged or key != "metadata"
|
|
}), parent_model)
|
|
|
|
|
|
def _request(app: FastAPI) -> Request:
|
|
return Request(TypeAdapter(dict[str, object]).validate_python(MappingProxyType({
|
|
"type": "http", "app": app, "scheme": "https", "server": ("proxy.test", 443),
|
|
"path": "/gateway/parent", "root_path": "/gateway", "query_string": b"parent=1",
|
|
"client": ("192.0.2.1", 4321), "headers": _HEADERS,
|
|
})))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("protocol", ("chat", "messages"))
|
|
async def test_child_preserves_credentials_and_isolates_context(protocol: Literal["chat", "messages"]) -> None:
|
|
app: Final = FastAPI()
|
|
stash: Final = get_or_create_request_stash()
|
|
|
|
@app.post("/v1/chat/completions" if protocol == "chat" else "/v1/messages")
|
|
async def endpoint(request: Request) -> Mapping[str, object]:
|
|
assert get_request_stash() is None and compaction_executor.get() is None
|
|
assert request.client == ("192.0.2.1", 4321) and request.url.scheme == "https"
|
|
assert request.scope["root_path"] == "/gateway" and request.cookies["session"] == "fixture"
|
|
assert request.headers["authorization"] == "Bearer sk-compaction-fixture" and not request.query_params
|
|
assert "x-litellm-call-id" not in request.headers
|
|
assert "litellm-disable-message-redaction" not in request.headers
|
|
assert int(request.headers["content-length"]) == len(await request.body())
|
|
with pytest.raises(BadRequestError, match="regular model group"):
|
|
reject_recursive_compactor("auto-router")
|
|
return MappingProxyType({"summary": "compacted"})
|
|
|
|
with inherit_message_logging_privacy(True):
|
|
assert (await with_proxy_compaction_executor(_child(protocol), _request(app)))["summary"] == "compacted"
|
|
assert get_request_stash() is stash and compaction_executor.get() is None
|
|
reject_recursive_compactor("auto-router")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("protocol", ("chat", "messages"))
|
|
@pytest.mark.parametrize("policy", ("allowed", "denied", "forged", "router_alias", "unrelated_alias"))
|
|
async def test_real_proxy_child_auth_privacy_and_body_policy(
|
|
monkeypatch: pytest.MonkeyPatch, protocol: Literal["chat", "messages"], policy: str,
|
|
) -> None:
|
|
cache: Final = UserApiKeyCache()
|
|
token: Final = proxy_server.hash_token("sk-compaction-fixture")
|
|
models: Final = {"denied": ("answer",), "router_alias": ("auto",), "unrelated_alias": ("other-auto",)}.get(policy, ("compactor",))
|
|
auth: Final = UserAPIKeyAuth.model_validate(MappingProxyType({"token": token, "models": models}))
|
|
await cache.async_set_cache(key=token, value=auth)
|
|
dispatched: Final = asyncio.Event()
|
|
allowed: Final = policy in ("allowed", "router_alias")
|
|
|
|
async def route(
|
|
data: Mapping[str, object], llm_router: Router | None, user_model: str | None,
|
|
route_type: str, user_api_key_dict: UserAPIKeyAuth | None,
|
|
) -> Awaitable[ModelResponse]:
|
|
dispatched.set()
|
|
assert allowed
|
|
if policy == "router_alias":
|
|
with pytest.raises(ProxyException):
|
|
await can_key_call_model("unrelated-compactor", None, auth, None)
|
|
assert (data["num_retries"], data["timeout"], data["stream_timeout"]) == (0, 7, 7)
|
|
assert data["disable_fallbacks"] is True and data["stream"] is False
|
|
logging: Final = data["litellm_logging_obj"]
|
|
assert isinstance(logging, Logging)
|
|
assert logging.standard_callback_dynamic_params.get("turn_off_message_logging") is True
|
|
assert should_redact_message_logging(TypeAdapter(dict[str, object]).validate_python(MappingProxyType({
|
|
"litellm_params": data, "standard_callback_dynamic_params": logging.standard_callback_dynamic_params,
|
|
})))
|
|
return asyncio.sleep(0, result=ModelResponse(id="private-summary", model="compactor"))
|
|
|
|
monkeypatch.setattr(litellm, "max_budget", 0)
|
|
monkeypatch.setattr(proxy_server.app, "dependency_overrides", {})
|
|
monkeypatch.setattr(proxy_server, "master_key", "sk-master-fixture")
|
|
monkeypatch.setattr(litellm, "max_budget", 0.0)
|
|
monkeypatch.setattr(proxy_server, "prisma_client", prisma_with_empty_config())
|
|
monkeypatch.setattr(proxy_server, "user_api_key_cache", cache)
|
|
monkeypatch.setattr(proxy_server, "llm_router", None)
|
|
monkeypatch.setattr(proxy_server, "general_settings", {})
|
|
monkeypatch.setattr(common_request_processing, "route_request", route)
|
|
with inherit_message_logging_privacy(True):
|
|
call: Final = with_proxy_compaction_executor(
|
|
_child(protocol, policy == "forged", "auto" if policy.endswith("alias") else None), _request(proxy_server.app)
|
|
)
|
|
if allowed:
|
|
assert (await call)["id"] == "private-summary"
|
|
else:
|
|
status: Final = 401 if policy == "forged" else 403
|
|
with pytest.raises(BadRequestError, match=rf"child request failed \(HTTP {status}\)"):
|
|
await call
|
|
assert dispatched.is_set() is allowed
|
|
assert compaction_executor.get() is None
|
|
if policy.endswith("alias"):
|
|
with pytest.raises(ProxyException):
|
|
await can_key_call_model("compactor", None, auth, None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("timeout", [False, True])
|
|
async def test_cancelling_parent_cancels_and_drains_child(timeout: bool) -> None:
|
|
app: Final = FastAPI()
|
|
started: Final = asyncio.Event()
|
|
stopped: Final = asyncio.Event()
|
|
|
|
@app.post("/v1/chat/completions")
|
|
async def endpoint() -> None:
|
|
started.set()
|
|
try:
|
|
await asyncio.Event().wait()
|
|
finally:
|
|
stopped.set()
|
|
|
|
parent: Final = asyncio.create_task(with_proxy_compaction_executor(_child(), _request(app)))
|
|
await asyncio.wait_for(started.wait(), timeout=5)
|
|
if timeout:
|
|
with pytest.raises(asyncio.TimeoutError):
|
|
await asyncio.wait_for(parent, timeout=0)
|
|
else:
|
|
parent.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await parent
|
|
assert stopped.is_set() and compaction_executor.get() is None
|