mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-26 22:30:11 +00:00
* feat(anthropic): workload identity federation and pluggable identity sources Backend half of #38818 (internal copy of the fork PR #38013), rebuilt as one commit on top of litellm_internal_staging without the dashboard changes. Deployments on anthropic/ without a static api_key can exchange an OIDC workload assertion for a short-lived sk-ant-oat01 token through a shared RFC 7523 JWT-bearer engine. The assertion comes from a mounted token file, an env token, a LiteLLM-signed issuer, or Keycloak, chosen per deployment, per named credential, or through ANTHROPIC_IDENTITY_SOURCE. The federation fields are server-owned: refused inline in request bodies and on POST /model/new, proxy-admin only on credentials, and the token exchange is pinned to api.anthropic.com unless LITELLM_ANTHROPIC_WIF_ALLOWED_HOSTS adds a host. GET /credentials/{name}/jwks exports the public key set of a LiteLLM-signed credential for the Claude Console. The OpenAI federation trio from #39613 rides along on the backend side with the same server-owned handling. Fixes #28607 Resolves LIT-6107 Co-authored-by: derhornspieler <15236687+derhornspieler@users.noreply.github.com> * fix(anthropic): let batch-result downloads mint from deployment params and accept host:port allowlist entries The files handler enabled workload identity on batch-result downloads but never received the deployment's litellm_params, so a deployment authenticating through a named credential could only mint from process-wide env vars. It now threads litellm_params through to the auth header the way the batch retrieve path already does. LITELLM_ANTHROPIC_WIF_ALLOWED_HOSTS entries written as host:port were read by urlsplit as a scheme, so the allowlist kept the raw entry while the exchange compared bare hostnames and refused the gateway. Entries are now parsed as network locations whether or not they carry a scheme. * fix(types): move the WIF kwargs key sets to a leaf module so the kwargs funnel imports without a cycle * test(anthropic): pin case-insensitive matching of WIF exchange-host allowlist entries * fix(anthropic): end workload identity federation errors without a period so the router suffix reads cleanly * fix(proxy): decrypt stored litellm_params before the WIF write gate * fix(proxy): hide WIF secret references from /health output * fix(proxy): keep the proxy error shape on credential endpoint refusals * fix(proxy): hide identity token file paths from /health output * fix(anthropic): rename the federation workspace param so Bedrock's anthropic_workspace_id keeps working The Bedrock Claude Platform route already reads anthropic_workspace_id from optional_params, so banning that spelling as a server-owned federation parameter broke a pre-existing client capability. The federation field is now anthropic_federation_workspace_id (env ANTHROPIC_FEDERATION_WORKSPACE_ID), which restores the base branch's behavior for Bedrock callers, drops the Bedrock-specific hint from the refusal message, and deletes the unconditional ban constant that no longer had a reader * fix(auth): share one exchanged token across workers reading the same assertion Anthropic accepts each identity assertion exactly once, so two uvicorn workers reading the same token file both minting from it means the second exchange is denied with jti_reused. Minted tokens now land in a per-user 0700 cache directory guarded by a file lock, so workers on the same host reuse one exchange until the token expires or the assertion rotates. A 401 is only retried when the re-read assertion actually differs, and the denial hint explains jti_reused. LITELLM_TOKEN_EXCHANGE_CACHE_DIR moves the cache and an empty value disables it * fix: keep anthropic federation from being shadowed or leaked An empty or whitespace-only ANTHROPIC_API_KEY counted as set, so a federated deployment sent an empty x-api-key on every call instead of minting a token. Blank values now read as unset, and a real static key on a federated deployment logs once that it outranks federation and nothing is being federated. The exchange-host allowlist matched hostnames only, so a second process on another port of an allowed host was trusted with the workload's identity token. An entry that names a port now trusts that port alone, while a bare host still trusts every port. The shared token store exists so the workers reading one projected token file do not each spend its single-use jti. A source that mints its own assertion per exchange shares nothing with another worker, so it no longer writes a live token to disk for a lookup that can never hit. * fix: unlink a staged token file a failed write leaves behind The 401 denial hint now also says federation ignores ANTHROPIC_WORKSPACE_ID, which the Bedrock Claude platform provider already reads. * refactor: move anthropic jwks derivation behind a provider-owned tagged union * fix: unlink the staged token file when its write fails at close A buffered write only reaches the disk when the handle closes, so a full disk surfaces at close and left the staging file behind holding a usable token. * fix(anthropic): close the staging descriptor before writing the shared token file * fix(wif): judge federation writes by what they set, not what is stored The admin gate read the stored deployment, so a team admin lost edit, delete and Test Connection on any deployment carrying federation params. It now returns early unless the submitted fields touch the federation surface, and a Test Connection probe that points the deployment at its own api_base is still refused, with the 403 no longer wrapped into a 500 The rest of the same review pass: POST /model/new refuses only a blocking value of `blocked`, so a client that always sends `blocked: false` is not turned away; a request body can no longer pick which federated identity to mint as by naming a stored credential; an advisory refresh the executor refuses disarms the entry instead of wedging the identity until the follower timeout; the static-key shadow warning resolves its env fallback inside the cache instead of once per request; credential writes drop nulls before storing them; the token exchange validates the endpoint URL before reading an assertion and keeps refusing redirects across a client heal; /health hides every server-owned federation field from non-admins; and the async create_file and create_batch paths say which setting is missing when the provider resolves no URL * fix(proxy): let a deployment write name a federated credential reject_federated_credential_reference runs from is_request_body_safe, which pre_db_read_auth_checks calls on every route, so it also fired on POST /model/new, /model/update, /model/{id}/update and /health/test_connection. A proxy admin could no longer attach a federated credential to a deployment over the API or the Admin UI, leaving a static config.yaml entry as the only way to configure the feature the rejection told the caller to go configure, and _reject_non_admin_wif_write never got to make the call it exists to make. is_request_body_safe now takes the route and skips only the credential-reference check on the routes that reach can_user_make_model_call. Federation fields typed inline into a body stay refused everywhere, and a call naming a federated credential still cannot pick the identity it mints as. * refactor(proxy): derive health display policy from the federation key sets The health check module hand-copied the five workload identity fields whose value is a credential, so a shared proxy surface named provider-specific parameters and a newly added secret-bearing field would have gone on being displayed until someone remembered both places WIF_SECRET_BEARING_KEYS now sits beside the key sets it splits out of, types/utils derives secret_bearing_wif_litellm_params from it, and the health layer splats that tuple the same way it already splats the admin-only one * fix(anthropic_wif): treat blank identity-source fields as unset * test(proxy): classify the federation params in the credential slot registry main's registry test (#43298) now fails the build for any credential-named deployment param without a classification. The five federation fields that carry a token, a token file path, or a signing or client secret reference are Unplanted, matching WIF_SECRET_BEARING_KEYS; the four remaining Keycloak settings name a URL, a client id, an auth method, or a scope and are NotSecret * fix(anthropic_wif): declare federation params as owned connection leaves and chart their metrics Register the 18 Anthropic and 3 OpenAI federation params as frozen ConnectionSettings leaves so the owned-kwarg registry, the kwargs funnel and the request-body ban list read one declaration. Pass the deployment api_base through to the count-tokens handler instead of a pre-suffixed URL, which doubled the /count_tokens path on main's prompt-cache predictor. Add the five litellm_anthropic_wif_* families to the all-metrics Grafana dashboard. * fix(credentials): gate PATCH on WIF fields resolved from model_id The credential PATCH handler checked server-owned workload identity federation fields only on the values the caller sent, while a body that named a deployment through model_id had its credential values resolved after that check. A non-admin could therefore copy a federated deployment's WIF fields onto an ordinary credential. Resolve the incoming values first and run the non-admin gate on them, matching the POST path * fix(anthropic): count tokens with ANTHROPIC_AUTH_TOKEN through the shared auth header Count-tokens walked its own credential ladder: a static key, else skip minting when ANTHROPIC_AUTH_TOKEN is set, else mint a federated token. With only the auth token set it forwarded nothing and the proxy silently fell back to its local tokenizer while chat on the same deployment authenticated with that token. The handler now takes the auth header that AnthropicModelInfo.aget_auth_header resolves, the same ladder chat, files, batches and skills use, and merges the oauth beta a minted or consumer token carries with the token-counting beta --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: derhornspieler <15236687+derhornspieler@users.noreply.github.com> Co-authored-by: mateo-berri <happymvw@gmail.com>
356 lines
13 KiB
Python
356 lines
13 KiB
Python
"""
|
|
Unit tests for litellm/llms/anthropic/batches/handler.py
|
|
|
|
AnthropicBatchesHandler is the HTTP/auth glue for retrieving Anthropic Message
|
|
Batches. It resolves credentials, builds the retrieve URL + auth headers via the
|
|
provider config, fires a single GET against the async httpx client, and hands the
|
|
response to the config's transform. These tests mock ONLY the genuine I/O seams -
|
|
the async httpx client (network) and credential resolution (secret managers /
|
|
env) - and assert exactly which seam fired, with what URL/headers, and that the
|
|
parsed result is the LiteLLMBatch the transform produced.
|
|
|
|
The sync ``retrieve_batch`` dispatch (``_is_async`` true -> coroutine, false ->
|
|
asyncio.run) is exercised directly.
|
|
"""
|
|
|
|
import asyncio
|
|
import threading
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
|
|
from litellm.llms.anthropic.batches.handler import AnthropicBatchesHandler
|
|
from litellm.types.utils import LiteLLMBatch
|
|
|
|
|
|
def _ok_batch_response():
|
|
"""A real httpx.Response shaped like an Anthropic MessageBatch retrieval."""
|
|
return httpx.Response(
|
|
status_code=200,
|
|
json={
|
|
"id": "msgbatch_abc",
|
|
"processing_status": "ended",
|
|
"created_at": "2024-09-24T10:00:00Z",
|
|
"ended_at": "2024-09-24T11:00:00Z",
|
|
"request_counts": {"succeeded": 2, "errored": 0},
|
|
},
|
|
request=httpx.Request("GET", "https://api.anthropic.com/v1/messages/batches/msgbatch_abc"),
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def handler():
|
|
return AnthropicBatchesHandler()
|
|
|
|
|
|
@pytest.fixture
|
|
def patched_client():
|
|
"""Patch the async httpx client seam; yield the (fake_client, factory)."""
|
|
fake_client = MagicMock()
|
|
fake_client.get = AsyncMock(return_value=_ok_batch_response())
|
|
with patch(
|
|
"litellm.llms.anthropic.batches.handler.get_async_httpx_client",
|
|
return_value=fake_client,
|
|
) as factory:
|
|
yield fake_client, factory
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_fires_get_with_correct_url_and_headers(handler, patched_client):
|
|
fake_client, factory = patched_client
|
|
|
|
batch = await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
|
|
# The single network seam fired exactly once.
|
|
fake_client.get.assert_awaited_once()
|
|
_, call_kwargs = fake_client.get.call_args
|
|
# Exact URL built by get_retrieve_batch_url.
|
|
assert call_kwargs["url"] == ("https://api.anthropic.com/v1/messages/batches/msgbatch_abc")
|
|
# Auth + version + beta headers built by validate_environment.
|
|
headers = call_kwargs["headers"]
|
|
assert headers["x-api-key"] == "sk-ant-test"
|
|
assert headers["anthropic-version"] == "2023-06-01"
|
|
assert headers["anthropic-beta"] == "message-batches-2024-09-24"
|
|
|
|
# Response parsed through the config transform.
|
|
assert isinstance(batch, LiteLLMBatch)
|
|
assert batch.id == "msgbatch_abc"
|
|
assert batch.status == "completed"
|
|
assert batch.request_counts.completed == 2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_uses_anthropic_provider_for_client(handler, patched_client):
|
|
from litellm.types.utils import LlmProviders
|
|
|
|
_, factory = patched_client
|
|
await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
_, kwargs = factory.call_args
|
|
assert kwargs["llm_provider"] == LlmProviders.ANTHROPIC
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_resolves_api_key_from_model_info(handler, patched_client):
|
|
fake_client, _ = patched_client
|
|
# api_key=None -> handler falls back to AnthropicModelInfo.get_api_key().
|
|
with patch.object(handler.anthropic_model_info, "get_api_key", return_value="sk-from-env"):
|
|
await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key=None,
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
_, call_kwargs = fake_client.get.call_args
|
|
assert call_kwargs["headers"]["x-api-key"] == "sk-from-env"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_missing_api_key_raises(handler, patched_client):
|
|
fake_client, _ = patched_client
|
|
# No api_key and resolver yields None -> hard error before any network call.
|
|
with patch.object(handler.anthropic_model_info, "get_api_key", return_value=None):
|
|
with pytest.raises(ValueError, match="Missing Anthropic API Key"):
|
|
await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key=None,
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
fake_client.get.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_resolves_default_api_base(handler, patched_client):
|
|
fake_client, _ = patched_client
|
|
# api_base=None -> resolved via get_api_base() default before URL build.
|
|
with patch.object(
|
|
handler.anthropic_model_info,
|
|
"get_api_base",
|
|
return_value="https://api.anthropic.com",
|
|
):
|
|
await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base=None,
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
_, call_kwargs = fake_client.get.call_args
|
|
assert call_kwargs["url"] == ("https://api.anthropic.com/v1/messages/batches/msgbatch_abc")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_raises_for_status(handler):
|
|
# A non-2xx response must surface via raise_for_status (no silent parse).
|
|
error_response = httpx.Response(
|
|
status_code=404,
|
|
json={"error": "not found"},
|
|
request=httpx.Request("GET", "https://api.anthropic.com/v1/messages/batches/missing"),
|
|
)
|
|
fake_client = MagicMock()
|
|
fake_client.get = AsyncMock(return_value=error_response)
|
|
with patch(
|
|
"litellm.llms.anthropic.batches.handler.get_async_httpx_client",
|
|
return_value=fake_client,
|
|
):
|
|
with pytest.raises(httpx.HTTPStatusError):
|
|
await handler.aretrieve_batch(
|
|
batch_id="missing",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_invokes_pre_call_logging(handler, patched_client):
|
|
fake_client, _ = patched_client
|
|
logging_obj = MagicMock()
|
|
await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
logging_obj=logging_obj,
|
|
)
|
|
logging_obj.pre_call.assert_called_once()
|
|
pre_kwargs = logging_obj.pre_call.call_args.kwargs
|
|
assert pre_kwargs["input"] == "msgbatch_abc"
|
|
assert pre_kwargs["api_key"] == "sk-ant-test"
|
|
# The logged api_base is the full retrieve URL, not the bare base.
|
|
assert pre_kwargs["additional_args"]["api_base"] == ("https://api.anthropic.com/v1/messages/batches/msgbatch_abc")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_builds_default_logging_obj_when_absent(handler, patched_client):
|
|
# logging_obj=None -> handler constructs a real Logging object; the call
|
|
# must still complete (no AttributeError on a missing logger).
|
|
_, _ = patched_client
|
|
with patch("litellm.litellm_core_utils.litellm_logging.Logging") as logging_cls:
|
|
logging_cls.return_value = MagicMock()
|
|
batch = await handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
logging_obj=None,
|
|
)
|
|
logging_cls.assert_called_once()
|
|
# call_type wires through to the constructed logging object.
|
|
assert logging_cls.call_args.kwargs["call_type"] == "batch_retrieve"
|
|
assert batch.id == "msgbatch_abc"
|
|
|
|
|
|
# =========================================================================== #
|
|
# retrieve_batch dispatch (sync wrapper)
|
|
# =========================================================================== #
|
|
|
|
|
|
async def test_retrieve_batch_async_returns_coroutine(handler, patched_client):
|
|
# _is_async=True -> returns the un-awaited coroutine (caller awaits it).
|
|
import asyncio
|
|
|
|
coro = handler.retrieve_batch(
|
|
_is_async=True,
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
assert asyncio.iscoroutine(coro)
|
|
# Await directly - robust under asyncio_mode=auto's session-scoped loop
|
|
# (manually driving get_event_loop().run_until_complete() breaks when prior
|
|
# async tests in the suite have already used/closed that loop).
|
|
batch = await coro
|
|
assert batch.id == "msgbatch_abc"
|
|
|
|
|
|
def test_retrieve_batch_sync_runs_to_result(handler, patched_client):
|
|
# _is_async=False -> asyncio.run(...) returns the resolved LiteLLMBatch.
|
|
batch = handler.retrieve_batch(
|
|
_is_async=False,
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key="sk-ant-test",
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
assert isinstance(batch, LiteLLMBatch)
|
|
assert batch.id == "msgbatch_abc"
|
|
assert batch.status == "completed"
|
|
|
|
|
|
# =========================================================================== #
|
|
# aretrieve_batch must not block the event loop on a WIF token exchange
|
|
# =========================================================================== #
|
|
|
|
_WIF_ENV = {
|
|
"ANTHROPIC_FEDERATION_RULE_ID": "fdrl_batches_seam",
|
|
"ANTHROPIC_ORGANIZATION_ID": "org-batches-seam",
|
|
"ANTHROPIC_IDENTITY_TOKEN": "batches-seam-inline-jwt",
|
|
}
|
|
|
|
|
|
class _BlockingPoster:
|
|
"""A token-endpoint poster that blocks until released, so the test can prove
|
|
the exchange ran off the event loop's own thread instead of freezing it."""
|
|
|
|
def __init__(self):
|
|
self.release = threading.Event()
|
|
self.thread_ids = []
|
|
|
|
def post(self, url, *, content, headers, timeout):
|
|
self.thread_ids.append(threading.get_ident())
|
|
self.release.wait(timeout=5)
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"access_token": "sk-ant-oat01-batches-seam",
|
|
"token_type": "Bearer",
|
|
"expires_in": 3600,
|
|
},
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aretrieve_batch_wif_exchange_does_not_block_event_loop(handler, patched_client, monkeypatch):
|
|
"""Regression: aretrieve_batch called the synchronous validate_environment
|
|
directly, so a cold WIF mint ran inline on the event loop and froze every
|
|
other concurrent coroutine until the exchange finished."""
|
|
from litellm.llms.anthropic import common_utils as anthropic_common_utils
|
|
from litellm.llms.anthropic.wif import get_anthropic_wif_token
|
|
from litellm.llms.base_llm.auth.token_exchange import JwtBearerTokenExchangeEngine
|
|
|
|
fake_client, _ = patched_client
|
|
for name in (
|
|
"ANTHROPIC_API_KEY",
|
|
"ANTHROPIC_AUTH_TOKEN",
|
|
"ANTHROPIC_API_BASE",
|
|
"ANTHROPIC_BASE_URL",
|
|
):
|
|
monkeypatch.delenv(name, raising=False)
|
|
for name, value in _WIF_ENV.items():
|
|
monkeypatch.setenv(name, value)
|
|
|
|
poster = _BlockingPoster()
|
|
engine = JwtBearerTokenExchangeEngine(poster=poster)
|
|
|
|
def routed_through_injected_engine(litellm_params, api_base, model):
|
|
return get_anthropic_wif_token(litellm_params, api_base, model, engine)
|
|
|
|
monkeypatch.setattr(anthropic_common_utils, "get_anthropic_wif_token", routed_through_injected_engine)
|
|
|
|
ticks = []
|
|
|
|
async def ticker():
|
|
for i in range(20):
|
|
await asyncio.sleep(0.005)
|
|
ticks.append(i)
|
|
|
|
ticker_task = asyncio.create_task(ticker())
|
|
await asyncio.sleep(0.02)
|
|
|
|
retrieve_task = asyncio.create_task(
|
|
handler.aretrieve_batch(
|
|
batch_id="msgbatch_abc",
|
|
api_base="https://api.anthropic.com",
|
|
api_key=None,
|
|
timeout=60.0,
|
|
max_retries=0,
|
|
)
|
|
)
|
|
await asyncio.sleep(0.05)
|
|
# The ticker kept advancing while the token exchange was still blocked on
|
|
# poster.release, proving the exchange did not run on the event loop.
|
|
assert len(ticks) > 0
|
|
assert not retrieve_task.done()
|
|
|
|
poster.release.set()
|
|
batch = await retrieve_task
|
|
await ticker_task
|
|
|
|
assert batch.id == "msgbatch_abc"
|
|
assert poster.thread_ids
|
|
assert poster.thread_ids[0] != threading.get_ident()
|
|
sent_headers = fake_client.get.call_args.kwargs["headers"]
|
|
assert sent_headers["authorization"] == "Bearer sk-ant-oat01-batches-seam"
|