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
feat(azure): support credential chain for storage (#39229)
yucheng-berrie0e249225b1f
diff --git a/litellm/integrations/azure_storage/azure_storage.py b/litellm/integrations/azure_storage/azure_storage.pyindex cb7175691df..16ef6920114 100644--- a/litellm/integrations/azure_storage/azure_storage.py+++ b/litellm/integrations/azure_storage/azure_storage.py@@ -1,7 +1,9 @@import asyncioimport osimport time+from collections.abc import Callablefrom datetime import datetime, timedelta+from functools import cachefrom typing import Finalfrom litellm._logging import verbose_logger@@ -19,21 +21,40 @@ from litellm.llms.custom_httpx.http_handler import (get_async_httpx_client,httpxSpecialProvider,)+from litellm.secret_managers.get_azure_ad_token_provider import (+ get_azure_ad_token_provider,+)+from litellm.types.secret_managers.get_azure_ad_token_provider import (+ AzureCredentialType,+)from litellm.types.utils import StandardLoggingPayload+AZURE_STORAGE_TOKEN_SCOPE: Final = "https://storage.azure.com/.default"+++@cache+def _cached_credential_chain_token_provider() -> Callable[[], str]:+ return get_azure_ad_token_provider(+ azure_scope=AZURE_STORAGE_TOKEN_SCOPE,+ azure_credential=AzureCredentialType.DefaultAzureCredential,+ )+class AzureBlobStorageLogger(CustomBatchLogger):def __init__(self,+ build_credential_chain_token_provider: Callable[+ [], Callable[[], str]+ ] = _cached_credential_chain_token_provider,**kwargs,):try:verbose_logger.debug("AzureBlobStorageLogger: in init azure blob storage logger")# Env Variables used for Azure Storage Authentication- self.tenant_id = os.getenv("AZURE_STORAGE_TENANT_ID")- self.client_id = os.getenv("AZURE_STORAGE_CLIENT_ID")- self.client_secret = os.getenv("AZURE_STORAGE_CLIENT_SECRET")+ self.tenant_id = os.getenv("AZURE_STORAGE_TENANT_ID") or None+ self.client_id = os.getenv("AZURE_STORAGE_CLIENT_ID") or None+ self.client_secret = os.getenv("AZURE_STORAGE_CLIENT_SECRET") or Noneself.azure_storage_account_key: str | None = os.getenv("AZURE_STORAGE_ACCOUNT_KEY")# Required Env Variables for Azure Storage@@ -55,6 +76,9 @@ class AzureBlobStorageLogger(CustomBatchLogger):# Internal variables used for Token based authenticationself.azure_auth_token: str | None = None # the Azure AD token to use for Azure Storage API requestsself.token_expiry: datetime | None = None # the expiry time of the currentAzure AD token+ self._build_credential_chain_token_provider: Callable[[], Callable[[], str]] = (+ build_credential_chain_token_provider+ )asyncio.create_task(self.periodic_flush())self.flush_lock = asyncio.Lock()@@ -231,10 +255,15 @@ class AzureBlobStorageLogger(CustomBatchLogger):"""Wrapper to set self.azure_auth_token to a valid Azure AD token, refreshing if necessary- Refreshes the token when:- - Token is expired- - Token is not set+ Without a service principal configured, the credential chain provider is read every+ time; it caches internally and refreshes against the token's real expiry. The read runs+ in a worker thread because the chain walk (IMDS probe, CLI subprocess) is blocking"""+ if self.tenant_id is None and self.client_id is None and self.client_secret is None:+ token_provider: Final = self._build_credential_chain_token_provider()+ self.azure_auth_token = await asyncio.to_thread(token_provider)+ return+# Check if token needs refreshif self._azure_ad_token_is_expired() or self.azure_auth_token is None:verbose_logger.debug("Azure AD token needs refresh")@@ -273,13 +302,9 @@ class AzureBlobStorageLogger(CustomBatchLogger):tenant_id=tenant_id,client_id=client_id,client_secret=client_secret,- scope="https://storage.azure.com/.default",+ scope=AZURE_STORAGE_TOKEN_SCOPE,)- token: Final = token_provider()-- verbose_logger.debug("azure auth token %s", token)-- return token+ return token_provider()def _azure_ad_token_is_expired(self):"""diff --git a/tests/test_litellm/integrations/azure_storage/test_azure_storage.py b/tests/test_litellm/integrations/azure_storage/test_azure_storage.pyindex 16c518ff412..a96eae0f9c3 100644--- a/tests/test_litellm/integrations/azure_storage/test_azure_storage.py+++ b/tests/test_litellm/integrations/azure_storage/test_azure_storage.py@@ -1,10 +1,15 @@+import asyncioimport sys+import threadingfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest--from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLogger+from litellm.integrations.azure_storage.azure_storage import (+ AzureBlobStorageLogger,+ _cached_credential_chain_token_provider,+)+from litellm.types.secret_managers.get_azure_ad_token_provider import AzureCredentialTypefrom litellm.types.utils import StandardLoggingPayload@@ -25,6 +30,26 @@ def mock_gov_env_vars(mock_env_vars, monkeypatch):monkeypatch.setenv("AZURE_STORAGE_ENDPOINT_SUFFIX", "core.usgovcloudapi.net")+def workload_identity_env_vars(monkeypatch):+ monkeypatch.setenv("AZURE_STORAGE_ACCOUNT_NAME", "test-account")+ monkeypatch.setenv("AZURE_STORAGE_FILE_SYSTEM", "test-container")+ for unset in (+ "AZURE_STORAGE_TENANT_ID",+ "AZURE_STORAGE_CLIENT_ID",+ "AZURE_STORAGE_CLIENT_SECRET",+ "AZURE_STORAGE_ACCOUNT_KEY",+ "AZURE_STORAGE_ENDPOINT_SUFFIX",+ "AZURE_CLIENT_SECRET",+ "AZURE_CREDENTIAL",+ "AZURE_SCOPE",+ ):+ monkeypatch.delenv(unset, raising=False)+ monkeypatch.setenv("AZURE_CLIENT_ID", "workload-identity-client-id")+ monkeypatch.setenv("AZURE_TENANT_ID", "workload-identity-tenant-id")+ monkeypatch.setenv("AZURE_FEDERATED_TOKEN_FILE", "/var/run/secrets/azure/tokens/azure-identity-token")++@pytest.mark.asyncioasync def test_async_upload_payload_to_azure_blob_storage(mock_env_vars):"""@@ -32,17 +57,12 @@ async def test_async_upload_payload_to_azure_blob_storage(mock_env_vars):a payload to Azure Blob Storage using the 3-step process (create, append, flush)."""with (- patch(- "litellm.integrations.azure_storage.azure_storage.get_async_httpx_client"- ) as mock_get_client,- patch(- "litellm.llms.azure.common_utils.get_azure_ad_token_from_entra_id"- ) as mock_get_token,+ patch("litellm.integrations.azure_storage.azure_storage.get_async_httpx_client") as mock_get_client,+ patch("litellm.integrations.azure_storage.azure_storage.get_azure_ad_token_from_entra_id") as mock_get_token,):# Create mock HTTP clientmock_http_client = AsyncMock()- mock_response = AsyncMock()- mock_response.raise_for_status = AsyncMock()+ mock_response = MagicMock()mock_http_client.put.return_value = mock_responsemock_http_client.patch.return_value = mock_responsemock_get_client.return_value = mock_http_client@@ -79,9 +99,7 @@ async def test_async_upload_payload_to_azure_blob_storage(mock_env_vars):put_call_args = mock_http_client.put.call_argsassert put_call_args[0][0] == f"{expected_base_url}?resource=file"assert put_call_args[1]["headers"]["x-ms-version"] is not None- assert (- put_call_args[1]["headers"]["Authorization"] == "Bearer mock-azure-ad-token"- )+ assert put_call_args[1]["headers"]["Authorization"] == "Bearer mock-azure-ad-token"# Step 2: Append dataassert mock_http_client.patch.call_count == 2 # Called for append and flush@@ -89,9 +107,7 @@ async def test_async_upload_payload_to_azure_blob_storage(mock_env_vars):assert append_call[0][0] == f"{expected_base_url}?action=append&position=0"assert append_call[1]["headers"]["x-ms-version"] is not Noneassert append_call[1]["headers"]["Content-Type"] == "application/json"- assert (- append_call[1]["headers"]["Authorization"] == "Bearer mock-azure-ad-token"- )+ assert append_call[1]["headers"]["Authorization"] == "Bearer mock-azure-ad-token"assert "test-log-id-123" in append_call[1]["data"]# Step 3: Flush data@@ -110,9 +126,7 @@ async def test_async_upload_payload_uses_configured_endpoint_suffix(mock_gov_envAZURE_STORAGE_ENDPOINT_SUFFIX must reach the Entra-ID REST upload path so asovereign-cloud account is addressed instead of the commercial dfs host."""- with patch(- "litellm.integrations.azure_storage.azure_storage.get_async_httpx_client"- ) as mock_get_client:+ with patch("litellm.integrations.azure_storage.azure_storage.get_async_httpx_client") as mock_get_client:mock_http_client = AsyncMock()mock_response = MagicMock()mock_http_client.put.return_value = mock_response@@ -127,17 +141,10 @@ async def test_async_upload_payload_uses_configured_endpoint_suffix(mock_gov_envawait logger.async_upload_payload_to_azure_blob_storage(test_payload)- expected_base_url = (- "https://test-account.dfs.core.usgovcloudapi.net/test-container/gov-log-id.json"- )+ expected_base_url = "https://test-account.dfs.core.usgovcloudapi.net/test-container/gov-log-id.json"assert mock_http_client.put.call_args[0][0] == f"{expected_base_url}?resource=file"- assert (- mock_http_client.patch.call_args_list[0][0][0]- == f"{expected_base_url}?action=append&position=0"- )- assert mock_http_client.patch.call_args_list[1][0][0].startswith(- f"{expected_base_url}?action=flush"- )+ assert mock_http_client.patch.call_args_list[0][0][0] == f"{expected_base_url}?action=append&position=0"+ assert mock_http_client.patch.call_args_list[1][0][0].startswith(f"{expected_base_url}?action=flush")@pytest.mark.asyncio@@ -148,9 +155,7 @@ async def test_service_client_uses_configured_endpoint_suffix(mock_gov_env_vars)"""fake_aio_module = MagicMock()- with patch.dict(- sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}- ):+ with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):logger = AzureBlobStorageLogger()await logger.get_service_client()@@ -160,14 +165,180 @@ async def test_service_client_uses_configured_endpoint_suffix(mock_gov_env_vars))+async def test_upload_authenticates_through_the_credential_chain_under_workload_identity(+ workload_identity_env_vars,+):+ build_provider = MagicMock(return_value=lambda: "workload-identity-token")+ with patch( # test-quality-ok: REST client is created inside the method; assert emitted request headers+ "litellm.integrations.azure_storage.azure_storage.get_async_httpx_client"+ ) as mock_get_client:+ mock_http_client = AsyncMock()+ mock_http_client.put.return_value = MagicMock()+ mock_http_client.patch.return_value = MagicMock()+ mock_get_client.return_value = mock_http_client++ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=build_provider)+ await logger.async_upload_payload_to_azure_blob_storage({"id": "wif-log-id"})++ build_provider.assert_called_once_with()+ assert logger.azure_auth_token == "workload-identity-token"+ sent_headers = [mock_http_client.put.call_args[1]["headers"]] + [+ call[1]["headers"] for call in mock_http_client.patch.call_args_list+ ]+ assert len(sent_headers) == 3+ assert all(headers["Authorization"] == "Bearer workload-identity-token" for headers in sent_headers)+++def test_default_chain_provider_is_storage_scoped_and_built_once_per_process():+ _cached_credential_chain_token_provider.cache_clear()+ with (+ patch( # test-quality-ok: assert the default factory's fixed scope and credential type without constructing Azure SDK credentials+ "litellm.integrations.azure_storage.azure_storage.get_azure_ad_token_provider",+ return_value=lambda: "chain-token",+ ) as mock_builder+ ):+ first = _cached_credential_chain_token_provider()+ second = _cached_credential_chain_token_provider()+ _cached_credential_chain_token_provider.cache_clear()++ assert first is second+ assert first() == "chain-token"+ mock_builder.assert_called_once_with(+ azure_scope="https://storage.azure.com/.default",+ azure_credential=AzureCredentialType.DefaultAzureCredential,+ )+++async def test_chain_tokens_are_read_from_the_provider_on_every_refresh(+ workload_identity_env_vars,+):+ provider = MagicMock(side_effect=["chain-token-1", "chain-token-2"])+ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=MagicMock(return_value=provider))+ await logger.set_valid_azure_ad_token()+ first_token = logger.azure_auth_token+ await logger.set_valid_azure_ad_token()++ assert first_token == "chain-token-1"+ assert logger.azure_auth_token == "chain-token-2"+ assert provider.call_count == 2+++async def test_chain_token_read_yields_to_the_event_loop(workload_identity_env_vars):+ """+ The chain walk is blocking I/O (IMDS probe, CLI subprocess), so reading the provider+ inline would stall every request on the worker. Prove other coroutines run during the read.+ """+ loop_was_free = threading.Event()++ def provider() -> str:+ if not loop_was_free.wait(timeout=5):+ raise TimeoutError("the event loop never ran the observer while the token was being read")+ return "chain-token"++ async def observer():+ loop_was_free.set()++ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=MagicMock(return_value=provider))+ observer_task = asyncio.create_task(observer())+ await logger.set_valid_azure_ad_token()+ await observer_task++ assert logger.azure_auth_token == "chain-token"+++async def test_empty_string_service_principal_vars_still_use_the_credential_chain(+ workload_identity_env_vars, monkeypatch+):+ for name in ("AZURE_STORAGE_TENANT_ID", "AZURE_STORAGE_CLIENT_ID", "AZURE_STORAGE_CLIENT_SECRET"):+ monkeypatch.setenv(name, "")++ logger = AzureBlobStorageLogger(+ build_credential_chain_token_provider=MagicMock(return_value=lambda: "workload-identity-token")+ )+ await logger.set_valid_azure_ad_token()++ assert logger.azure_auth_token == "workload-identity-token"+++async def test_client_secret_auth_still_uses_the_storage_scoped_service_principal(mock_env_vars):+ build_provider = MagicMock()+ with (+ patch( # test-quality-ok: assert the storage scope passed to the shared token factory without making an external auth call+ "litellm.integrations.azure_storage.azure_storage.get_azure_ad_token_from_entra_id",+ return_value=lambda: "client-secret-token",+ ) as mock_entra_id+ ):+ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=build_provider)+ await logger.set_valid_azure_ad_token()++ assert logger.azure_auth_token == "client-secret-token"+ build_provider.assert_not_called()+ assert mock_entra_id.call_args.kwargs == {+ "tenant_id": "test-tenant-id",+ "client_id": "test-client-id",+ "client_secret": "test-client-secret",+ "scope": "https://storage.azure.com/.default",+ }+++ "missing_var",+ ["AZURE_STORAGE_TENANT_ID", "AZURE_STORAGE_CLIENT_ID", "AZURE_STORAGE_CLIENT_SECRET"],+)+async def test_partially_configured_service_principal_still_names_the_missing_variable(+ mock_env_vars, monkeypatch, missing_var+):+ monkeypatch.delenv(missing_var)++ build_provider = MagicMock()+ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=build_provider)+ with pytest.raises(ValueError, match=f"Missing required environment variable: {missing_var}"):+ await logger.set_valid_azure_ad_token()++ build_provider.assert_not_called()+++async def test_account_key_auth_never_requests_a_token(workload_identity_env_vars, monkeypatch):+ monkeypatch.setenv("AZURE_STORAGE_ACCOUNT_KEY", "dGVzdC1rZXk=")++ file_client = MagicMock()+ file_client.create_file = AsyncMock()+ file_client.append_data = AsyncMock()+ file_client.flush_data = AsyncMock()+ directory_client = MagicMock()+ directory_client.exists = AsyncMock(return_value=True)+ directory_client.get_file_client = MagicMock(return_value=file_client)+ file_system_client = MagicMock()+ file_system_client.get_directory_client = MagicMock(return_value=directory_client)+ service_client = MagicMock()+ service_client.get_file_system_client = MagicMock(return_value=file_system_client)+ fake_aio_module = MagicMock()+ fake_aio_module.DataLakeServiceClient = MagicMock(return_value=service_client)++ build_provider = MagicMock()+ with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):+ logger = AzureBlobStorageLogger(build_credential_chain_token_provider=build_provider)+ await logger.async_upload_payload_to_azure_blob_storage({"id": "account-key-log-id"})++ build_provider.assert_not_called()+ assert logger.azure_auth_token is None+ file_client.flush_data.assert_awaited_once()+ assert fake_aio_module.DataLakeServiceClient.call_args.kwargs["credential"] == "dGVzdC1rZXk="++@pytest.mark.asyncioasync def test_service_client_defaults_to_commercial_endpoint(mock_env_vars):"""Unset AZURE_STORAGE_ENDPOINT_SUFFIX keeps the pre-existing commercial host"""fake_aio_module = MagicMock()- with patch.dict(- sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}- ):+ with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):logger = AzureBlobStorageLogger()await logger.get_service_client()diff --git a/tests/test_litellm/llms/base_llm/files/test_azure_blob_storage_backend.py b/tests/test_litellm/llms/base_llm/files/test_azure_blob_storage_backend.pyindex 7e1139ca79a..222ead92b54 100644--- a/tests/test_litellm/llms/base_llm/files/test_azure_blob_storage_backend.py+++ b/tests/test_litellm/llms/base_llm/files/test_azure_blob_storage_backend.py@@ -27,6 +27,20 @@ def mock_gov_env_vars(mock_env_vars, monkeypatch):monkeypatch.setenv("AZURE_STORAGE_ENDPOINT_SUFFIX", GOV_SUFFIX)+def credential_chain_env_vars(monkeypatch):+ monkeypatch.setenv("AZURE_STORAGE_ACCOUNT_NAME", "test-account")+ monkeypatch.setenv("AZURE_STORAGE_FILE_SYSTEM", "test-container")+ for name in (+ "AZURE_STORAGE_TENANT_ID",+ "AZURE_STORAGE_CLIENT_ID",+ "AZURE_STORAGE_CLIENT_SECRET",+ "AZURE_STORAGE_ACCOUNT_KEY",+ "AZURE_STORAGE_ENDPOINT_SUFFIX",+ ):+ monkeypatch.delenv(name, raising=False)++def _make_backend() -> AzureBlobStorageBackend:backend = AzureBlobStorageBackend()backend.azure_auth_token = "mock-azure-ad-token"@@ -42,6 +56,29 @@ def _mock_upload_client() -> AsyncMock:return client+async def test_upload_file_with_credential_chain(credential_chain_env_vars):+ client = _mock_upload_client()+ build_provider = MagicMock(return_value=lambda: "workload-identity-token")++ with patch( # test-quality-ok: the backend creates its REST client internally; assert the emitted authorization header+ "litellm.llms.custom_httpx.http_handler.get_async_httpx_client", return_value=client+ ):+ backend = AzureBlobStorageBackend(build_credential_chain_token_provider=build_provider)+ storage_url = await backend.upload_file(+ file_content=b"hello",+ filename="report.json",+ content_type="application/json",+ path_prefix="logs",+ file_naming_strategy="original_filename",+ )++ build_provider.assert_called_once_with()+ assert storage_url == "https://test-account.blob.core.windows.net/test-container/logs/report.json"+ assert client.put.call_args[1]["headers"]["Authorization"] == "Bearer workload-identity-token"+ assert client.patch.call_count == 2++@pytest.mark.parametrize("env_fixture, expected_suffix",[("mock_env_vars", "core.windows.net"), ("mock_gov_env_vars", GOV_SUFFIX)],@@ -125,10 +162,7 @@ async def test_download_file_accepts_url_persisted_before_the_suffix_was_set(moc)assert content == b"file-bytes"- assert (- client.get.call_args[0][0]- == f"https://test-account.blob.{GOV_SUFFIX}/test-container/logs/report.json"- )+ assert client.get.call_args[0][0] == f"https://test-account.blob.{GOV_SUFFIX}/test-container/logs/report.json"@pytest.mark.parametrize(@@ -178,10 +212,7 @@ async def test_download_file_drops_query_string_from_the_stored_url(mock_env_var"https://test-account.blob.core.windows.net/test-container/logs/report.json?sig=redacted&se=2026")- assert (- client.get.call_args[0][0]- == "https://test-account.blob.core.windows.net/test-container/logs/report.json"- )+ assert client.get.call_args[0][0] == "https://test-account.blob.core.windows.net/test-container/logs/report.json"@pytest.mark.parametrize(