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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): resolve named credentials on provider-only batch and files calls
mateo-berri17ce2c4e9211
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.pyindex a2dc5e1caf5..a91b29002e3 100644--- a/litellm/proxy/batches_endpoints/endpoints.py+++ b/litellm/proxy/batches_endpoints/endpoints.py@@ -23,6 +23,7 @@ from litellm.proxy.common_utils.openai_endpoint_utils import ()from litellm.proxy.openai_files_endpoints.common_utils import (_is_base64_encoded_unified_file_id,+ apply_team_provider_credentials,decode_model_from_file_id,encode_batch_response_ids,encode_file_id_with_model,@@ -295,6 +296,12 @@ async def create_batch(verbose_proxy_logger.debug(f"Created batch using model: {model_param}")else:# SCENARIO 3: Fallback to custom_llm_provider (uses env variables)+ apply_team_provider_credentials(+ data=cast(dict, _create_batch_data), # cast-ok: TypedDict is a dict at runtime+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )response = await litellm.acreate_batch(custom_llm_provider=custom_llm_provider,**_create_batch_data, # type: ignore@@ -525,6 +532,12 @@ async def retrieve_batch(or get_custom_llm_provider_from_request_query(request=request)or "openai")+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )response = await litellm.aretrieve_batch(custom_llm_provider=custom_llm_provider,**data, # type: ignore@@ -718,6 +731,12 @@ async def list_batches(or get_custom_llm_provider_from_request_query(request=request)or "openai")+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )response = await litellm.alist_batches(custom_llm_provider=custom_llm_provider, # type: ignoreafter=after,@@ -908,6 +927,12 @@ async def cancel_batch(# Extract batch_id from data to avoid "multiple values for keyword argument" error# data was cast from CancelBatchRequest which already contains batch_iddata.pop("batch_id", None)+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )_cancel_batch_data = CancelBatchRequest(batch_id=batch_id, **data)response = await litellm.acancel_batch(custom_llm_provider=custom_llm_provider, # type: ignorediff --git a/litellm/proxy/openai_files_endpoints/common_utils.py b/litellm/proxy/openai_files_endpoints/common_utils.pyindex efd1d6b6cee..d4ac45559ee 100644--- a/litellm/proxy/openai_files_endpoints/common_utils.py+++ b/litellm/proxy/openai_files_endpoints/common_utils.py@@ -14,6 +14,7 @@ from litellm.types.utils import SpecialEnumsif TYPE_CHECKING:from fastapi import Request+ from litellm.proxy._types import UserAPIKeyAuthfrom litellm.router import Router@@ -373,6 +374,29 @@ def get_team_provider_credentials(return None+def apply_team_provider_credentials(+ data: dict, # mutable-ok: credentials are merged into the request payload in place, same contract as prepare_data_with_credentials+ llm_router: Optional["Router"],+ user_api_key_dict: "UserAPIKeyAuth",+ custom_llm_provider: str,+) -> None:+ """+ Resolve credentials for a provider-only request (no model pinned) via+ ``get_team_provider_credentials`` and merge them into ``data`` in-place.+ Leaves ``data`` untouched when no authorized deployment matches, so the+ caller falls back to environment-variable credentials exactly as before.+ """+ credentials = get_team_provider_credentials(+ llm_router=llm_router,+ team_models=user_api_key_dict.team_models or [],+ custom_llm_provider=custom_llm_provider,+ team_id=user_api_key_dict.team_id,+ )+ if credentials is None:+ return+ prepare_data_with_credentials(data=data, credentials=credentials)++def prepare_data_with_credentials(data: dict,credentials: dict,diff --git a/litellm/proxy/openai_files_endpoints/files_endpoints.py b/litellm/proxy/openai_files_endpoints/files_endpoints.pyindex 0c9aa667751..f1bcfbafe58 100644--- a/litellm/proxy/openai_files_endpoints/files_endpoints.py+++ b/litellm/proxy/openai_files_endpoints/files_endpoints.py@@ -43,10 +43,10 @@ from litellm.litellm_core_utils.cloud_storage_security import ()from litellm.proxy.openai_files_endpoints.common_utils import (_is_base64_encoded_unified_file_id,+ apply_team_provider_credentials,encode_file_id_with_model,extract_file_creation_params,get_credentials_for_model,- get_team_provider_credentials,handle_model_based_routing,prepare_data_with_credentials,validate_managed_files_requirement,@@ -253,6 +253,12 @@ async def route_create_file(_create_file_request=_create_file_request,)else:+ apply_team_provider_credentials(+ data=cast(dict, _create_file_request), # cast-ok: TypedDict is a plain dict at runtime; merged in place+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )# get configs for custom_llm_providerllm_provider_config = get_files_provider_config(custom_llm_provider=custom_llm_provider)if llm_provider_config is not None:@@ -735,6 +741,14 @@ async def get_file_content(check_file_id_encoding=True,)+ if not should_route:+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )+from litellm.proxy.openai_files_endpoints.file_content_streaming_handler import (FileContentStreamingHandler,)@@ -983,6 +997,12 @@ async def get_file(# Remove file_id from data to avoid "multiple values for keyword argument" error# data was initialized with {"file_id": file_id}data.pop("file_id", None)+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )response = await litellm.afile_retrieve(custom_llm_provider=custom_llm_provider,file_id=file_id,@@ -1183,6 +1203,12 @@ async def delete_file()else:data.pop("file_id", None)+ apply_team_provider_credentials(+ data=data,+ llm_router=llm_router,+ user_api_key_dict=user_api_key_dict,+ custom_llm_provider=custom_llm_provider,+ )response = await litellm.afile_delete(custom_llm_provider=custom_llm_provider,file_id=file_id,@@ -1354,14 +1380,12 @@ async def list_files(# No model/target_model_names pinned: resolve upstream credentials from# the team's deployment for this provider so the call is authenticated# against the team's own account (e.g. the team's openai deployment).- team_credentials = get_team_provider_credentials(+ apply_team_provider_credentials(+ data=data,llm_router=llm_router,- team_models=user_api_key_dict.team_models or [],+ user_api_key_dict=user_api_key_dict,custom_llm_provider=custom_llm_provider,- team_id=user_api_key_dict.team_id,)- if team_credentials is not None:- prepare_data_with_credentials(data=data, credentials=team_credentials)response = await litellm.afile_list(custom_llm_provider=custom_llm_provider,diff --git a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.pyindex 9573fddd435..6a185988c9b 100644--- a/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py+++ b/tests/test_litellm/proxy/batches_endpoints/test_endpoints.py@@ -51,7 +51,7 @@ from litellm.proxy.openai_files_endpoints.common_utils import (from litellm.proxy.utils import ProxyLoggingfrom litellm.router import Routerfrom litellm.types.llms.openai import BatchJobStatus-from litellm.types.utils import LiteLLMBatch+from litellm.types.utils import CredentialItem, LiteLLMBatchfrom fastapi import Response@@ -2091,3 +2091,154 @@ async def test_retrieve__unified_no_router_500(retrieve_harness):assert exc.value.code == "500"retrieve_harness.router_aretrieve.assert_not_called()retrieve_harness.litellm_aretrieve.assert_not_called()+++# =========================================================================== #+# SCENARIO 3 + configured deployments: a provider-only call (custom-llm-provider+# header, no model anywhere) must resolve the gateway/team deployment's named+# credential for that provider and attach it to the provider call kwargs,+# instead of silently falling through to the host environment's default+# credentials (regression: vertex batch jobs landing in the hosting env's GCP+# project because litellm_credential_name never reached the call).+# =========================================================================== #++VERTEX_NAMED_CREDENTIAL = CredentialItem(+ credential_name="vertex-named-cred",+ credential_info={},+ credential_values={+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ },+)+++def vertex_named_credential_router() -> Router:+ return Router(+ model_list=[+ {+ "model_name": "gemini-2.5-pro",+ "litellm_params": {+ "model": "vertex_ai/gemini-2.5-pro",+ "litellm_credential_name": "vertex-named-cred",+ },+ }+ ]+ )+++async def test_create__provider_only_resolves_named_vertex_credentials(harness):+ """Provider-only create must attach the configured named credential, and must+ NOT turn the call into a model-routed one (no model kwarg injected)."""+ set_body(+ harness,+ {+ "input_file_id": "file-plain",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h",+ },+ )+ harness.provider_from_headers.return_value = "vertex_ai"++ with patch.object(litellm, "credential_list", [VERTEX_NAMED_CREDENTIAL]):+ with patch.object(proxy_server, "llm_router", vertex_named_credential_router()):+ await call_create(harness)++ assert harness.acreate_kwargs() == {+ "custom_llm_provider": "vertex_ai",+ "input_file_id": "file-plain",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h",+ "metadata": None,+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ }+++async def test_create__provider_only_ignores_other_provider_deployments(harness):+ """A provider-only vertex call must not pick up credentials from deployments+ of a different provider; with no vertex deployment the payload is exactly the+ pre-fix env-var fallback."""+ set_body(+ harness,+ {+ "input_file_id": "file-plain",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h",+ },+ )+ harness.provider_from_headers.return_value = "vertex_ai"+ openai_only_router = Router(+ model_list=[+ {+ "model_name": "gpt-4o",+ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-global-openai"},+ }+ ]+ )++ with patch.object(proxy_server, "llm_router", openai_only_router):+ await call_create(harness)++ assert harness.acreate_kwargs() == {+ "custom_llm_provider": "vertex_ai",+ "input_file_id": "file-plain",+ "endpoint": "/v1/chat/completions",+ "completion_window": "24h",+ "metadata": None,+ }+++async def test_retrieve__provider_only_resolves_named_vertex_credentials(retrieve_harness):+ retrieve_harness.provider_from_headers.return_value = "vertex_ai"++ with patch.object(litellm, "credential_list", [VERTEX_NAMED_CREDENTIAL]):+ with patch.object(proxy_server, "llm_router", vertex_named_credential_router()):+ await call_retrieve(retrieve_harness, "batch-raw-xyz")++ assert retrieve_harness.aretrieve_kwargs() == {+ "custom_llm_provider": "vertex_ai",+ "batch_id": "batch-raw-xyz",+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ }+++async def test_list__provider_only_resolves_named_vertex_credentials(list_harness):+ list_harness.provider_from_headers.return_value = "vertex_ai"++ with patch.object(litellm, "credential_list", [VERTEX_NAMED_CREDENTIAL]):+ with patch.object(proxy_server, "llm_router", vertex_named_credential_router()):+ await call_list(list_harness)++ assert list_harness.alist_kwargs() == {+ "custom_llm_provider": "vertex_ai",+ "after": None,+ "limit": None,+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ }+++async def test_cancel__provider_only_resolves_named_vertex_credentials(cancel_harness):+ cancel_harness.provider_from_headers.return_value = "vertex_ai"++ with patch.object(litellm, "credential_list", [VERTEX_NAMED_CREDENTIAL]):+ with patch.object(proxy_server, "llm_router", vertex_named_credential_router()):+ await call_cancel(cancel_harness, "batch-raw-xyz")++ assert cancel_harness.acancel_kwargs() == {+ "custom_llm_provider": "vertex_ai",+ "batch_id": "batch-raw-xyz",+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ }diff --git a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.pyindex 46ecb31e1c8..23cd1c71cbe 100644--- a/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py+++ b/tests/test_litellm/proxy/openai_files_endpoint/test_files_endpoint.py@@ -2610,3 +2610,260 @@ def test_list_files_with_all_proxy_models_team_uses_openai_deployment(assert captured_kwargs.get("api_key") == "team-openai-key"assert captured_kwargs.get("custom_llm_provider") == "openai"proxy_logging_obj.post_call_failure_hook.assert_not_called()+++def _setup_vertex_named_credential_router(monkeypatch) -> Router:+ from litellm.types.utils import CredentialItem++ monkeypatch.setattr(+ litellm,+ "credential_list",+ [+ CredentialItem(+ credential_name="vertex-named-cred",+ credential_info={},+ credential_values={+ "vertex_project": "customer-project",+ "vertex_location": "us-central1",+ "vertex_credentials": "/creds/customer-sa.json",+ },+ )+ ],+ )+ return Router(+ model_list=[+ {+ "model_name": "gemini-2.5-pro",+ "litellm_params": {+ "model": "vertex_ai/gemini-2.5-pro",+ "litellm_credential_name": "vertex-named-cred",+ },+ }+ ]+ )+++def _assert_vertex_named_credentials_attached(captured_kwargs: dict) -> None:+ assert captured_kwargs.get("custom_llm_provider") == "vertex_ai"+ assert captured_kwargs.get("vertex_project") == "customer-project"+ assert captured_kwargs.get("vertex_location") == "us-central1"+ assert captured_kwargs.get("vertex_credentials") == "/creds/customer-sa.json"+ assert captured_kwargs.get("model") is None+++def test_create_file_provider_only_resolves_named_vertex_credentials(+ mocker: MockerFixture, monkeypatch+):+ """+ POST /v1/files with only a custom-llm-provider header (no model, no+ target_model_names) must attach the configured named vertex credential to+ the upstream call instead of falling through to google.auth.default(),+ which uploads into the hosting environment's GCP project.+ """+ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ router = _setup_vertex_named_credential_router(monkeypatch)+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_acreate_file(**kwargs):+ captured_kwargs.update(kwargs)+ return OpenAIFileObject(+ id="file-vertex-123",+ object="file",+ bytes=2,+ created_at=1234567890,+ filename="batch.jsonl",+ purpose="batch",+ status="uploaded",+ )++ monkeypatch.setattr(litellm, "acreate_file", _mock_acreate_file)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.post(+ "/v1/files",+ files={"file": ("batch.jsonl", b"{}", "application/jsonl")},+ data={"purpose": "batch"},+ headers={+ "Authorization": "Bearer test-key",+ "custom-llm-provider": "vertex_ai",+ },+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ _assert_vertex_named_credentials_attached(captured_kwargs)+ proxy_logging_obj.post_call_failure_hook.assert_not_called()+++def test_get_file_provider_only_resolves_named_vertex_credentials(+ mocker: MockerFixture, monkeypatch+):+ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ router = _setup_vertex_named_credential_router(monkeypatch)+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_afile_retrieve(**kwargs):+ captured_kwargs.update(kwargs)+ return OpenAIFileObject(+ id="file-abc123",+ object="file",+ bytes=2,+ created_at=1234567890,+ filename="batch.jsonl",+ purpose="batch",+ status="uploaded",+ )++ monkeypatch.setattr(litellm, "afile_retrieve", _mock_afile_retrieve)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.get(+ "/v1/files/file-abc123",+ headers={+ "Authorization": "Bearer test-key",+ "custom-llm-provider": "vertex_ai",+ },+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ assert captured_kwargs.get("file_id") == "file-abc123"+ _assert_vertex_named_credentials_attached(captured_kwargs)+ proxy_logging_obj.post_call_failure_hook.assert_not_called()+++def test_get_file_content_provider_only_resolves_named_vertex_credentials(+ mocker: MockerFixture, monkeypatch+):+ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ router = _setup_vertex_named_credential_router(monkeypatch)+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_afile_content(**kwargs):+ captured_kwargs.update(kwargs)+ return HttpxBinaryResponseContent(+ response=httpx.Response(+ status_code=200,+ content=b"vertex-bytes",+ headers={"content-type": "application/octet-stream"},+ )+ )++ monkeypatch.setattr(litellm, "afile_content", _mock_afile_content)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.get(+ "/v1/files/file-abc123/content",+ headers={+ "Authorization": "Bearer test-key",+ "custom-llm-provider": "vertex_ai",+ },+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ assert response.content == b"vertex-bytes"+ assert captured_kwargs.get("file_id") == "file-abc123"+ _assert_vertex_named_credentials_attached(captured_kwargs)+ proxy_logging_obj.post_call_failure_hook.assert_not_called()+++def test_delete_file_provider_only_resolves_named_vertex_credentials(+ mocker: MockerFixture, monkeypatch+):+ import litellm.proxy.proxy_server as ps+ from litellm.proxy._types import LitellmUserRoles++ router = _setup_vertex_named_credential_router(monkeypatch)+ proxy_logging_obj = setup_proxy_logging_object(monkeypatch, router)+ monkeypatch.setattr("litellm.proxy.proxy_server.master_key", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", router)+ proxy_logging_obj.update_request_status = mocker.AsyncMock()+ proxy_logging_obj.post_call_failure_hook = mocker.AsyncMock()++ captured_kwargs: dict = {}++ async def _mock_afile_delete(**kwargs):+ captured_kwargs.update(kwargs)+ return OpenAIFileObject(+ id="file-abc123",+ object="file",+ bytes=2,+ created_at=1234567890,+ filename="batch.jsonl",+ purpose="batch",+ status="uploaded",+ )++ monkeypatch.setattr(litellm, "afile_delete", _mock_afile_delete)++ app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(+ api_key="test-key",+ user_role=LitellmUserRoles.PROXY_ADMIN,+ user_id="test-user",+ )++ try:+ response = client.delete(+ "/v1/files/file-abc123",+ headers={+ "Authorization": "Bearer test-key",+ "custom-llm-provider": "vertex_ai",+ },+ )+ finally:+ app.dependency_overrides.pop(ps.user_api_key_auth, None)++ assert response.status_code == 200, response.text+ assert captured_kwargs.get("file_id") == "file-abc123"+ _assert_vertex_named_credentials_attached(captured_kwargs)+ proxy_logging_obj.post_call_failure_hook.assert_not_called()