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
import asyncio
import base64
import json
import re
import sys
import threading
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from litellm.constants import _DEFAULT_TTL_FOR_HTTPX_CLIENTS
from litellm.integrations.azure_storage import azure_storage as azure_storage_module
from litellm.integrations.azure_storage.azure_storage import (
AzureBlobStorageLogger,
_cached_credential_chain_token_provider,
adls_safe_file_name,
)
from litellm.types.secret_managers.get_azure_ad_token_provider import AzureCredentialType
from litellm.types.utils import StandardAuditLogPayload, StandardLoggingPayload
@pytest.fixture
def mock_env_vars(monkeypatch):
"""Set up required environment variables for Azure Storage"""
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT_NAME", "test-account")
monkeypatch.setenv("AZURE_STORAGE_FILE_SYSTEM", "test-container")
monkeypatch.setenv("AZURE_STORAGE_TENANT_ID", "test-tenant-id")
monkeypatch.setenv("AZURE_STORAGE_CLIENT_ID", "test-client-id")
monkeypatch.setenv("AZURE_STORAGE_CLIENT_SECRET", "test-client-secret")
monkeypatch.delenv("AZURE_STORAGE_ENDPOINT_SUFFIX", raising=False)
@pytest.fixture
def mock_gov_env_vars(mock_env_vars, monkeypatch):
"""Point the logger at an Azure Government storage account"""
monkeypatch.setenv("AZURE_STORAGE_ENDPOINT_SUFFIX", "core.usgovcloudapi.net")
@pytest.fixture
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_TOKEN_CREDENTIALS",
"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.asyncio
async def test_async_upload_payload_to_azure_blob_storage(mock_env_vars):
"""
Test that async_upload_payload_to_azure_blob_storage correctly uploads
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.integrations.azure_storage.azure_storage.get_azure_ad_token_from_entra_id") as mock_get_token,
):
# Create mock HTTP client
mock_http_client = AsyncMock()
mock_response = MagicMock()
mock_http_client.put.return_value = mock_response
mock_http_client.patch.return_value = mock_response
mock_get_client.return_value = mock_http_client
# Mock Azure AD token provider
mock_token_provider = MagicMock()
mock_token_provider.return_value = "mock-azure-ad-token"
mock_get_token.return_value = mock_token_provider
# Create logger instance
logger = AzureBlobStorageLogger()
# Set a valid token to avoid token refresh during test
logger.azure_auth_token = "mock-azure-ad-token"
logger.token_expiry = None # Set to None so token refresh check passes
# Create test payload
test_payload: StandardLoggingPayload = {
"id": "test-log-id-123",
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello"}],
}
# Call the method under test
await logger.async_upload_payload_to_azure_blob_storage(test_payload)
# Verify HTTP client was obtained
mock_get_client.assert_called_once()
# Verify the 3-step upload process was called correctly
# Step 1: Create file
expected_base_url = "https://test-account.dfs.core.windows.net/test-container/test-log-id-123.json"
mock_http_client.put.assert_called_once()
put_call_args = mock_http_client.put.call_args
assert 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"
# Step 2: Append data
assert mock_http_client.patch.call_count == 2 # Called for append and flush
append_call = mock_http_client.patch.call_args_list[0]
assert append_call[0][0] == f"{expected_base_url}?action=append&position=0"
assert append_call[1]["headers"]["x-ms-version"] is not None
assert append_call[1]["headers"]["Content-Type"] == "application/json"
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
flush_call = mock_http_client.patch.call_args_list[1]
assert "action=flush" in flush_call[0][0]
assert flush_call[1]["headers"]["x-ms-version"] is not None
assert flush_call[1]["headers"]["Authorization"] == "Bearer mock-azure-ad-token"
# Verify raise_for_status was called on all responses
assert mock_response.raise_for_status.call_count == 3
@pytest.mark.asyncio
async def test_async_upload_payload_uses_configured_endpoint_suffix(mock_gov_env_vars):
"""
AZURE_STORAGE_ENDPOINT_SUFFIX must reach the Entra-ID REST upload path so a
sovereign-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:
mock_http_client = AsyncMock()
mock_response = MagicMock()
mock_http_client.put.return_value = mock_response
mock_http_client.patch.return_value = mock_response
mock_get_client.return_value = mock_http_client
logger = AzureBlobStorageLogger()
logger.azure_auth_token = "mock-azure-ad-token"
logger.token_expiry = None
test_payload: StandardLoggingPayload = {"id": "gov-log-id"}
await 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"
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")
@pytest.mark.asyncio
async def test_service_client_uses_configured_endpoint_suffix(mock_gov_env_vars):
"""
The account key path builds its own account_url; the Azure SDK derives the blob
host from it, so the suffix has to be applied here too.
"""
fake_aio_module = MagicMock()
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger()
await logger.get_service_client()
assert (
fake_aio_module.DataLakeServiceClient.call_args.kwargs["account_url"]
== "https://test-account.dfs.core.usgovcloudapi.net"
)
@pytest.mark.asyncio
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.DeploymentIdentityCredential,
)
def test_storage_chain_reaches_only_the_identities_a_deployment_carries(workload_identity_env_vars):
"""
The chain runs on a server, where a developer sign-in is a person and not the deployment, so
the storage token must come from workload identity or managed identity or from nothing
"""
_cached_credential_chain_token_provider.cache_clear()
with patch("azure.identity.get_bearer_token_provider", return_value=lambda: "chain-token") as bearer:
_cached_credential_chain_token_provider()
_cached_credential_chain_token_provider.cache_clear()
bearer.assert_called_once()
with bearer.call_args.args[0] as chain:
assert {type(link).__name__ for link in chain.credentials} == {
"WorkloadIdentityCredential",
"ManagedIdentityCredential",
}
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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",
}
@pytest.mark.parametrize(
"missing_var",
["AZURE_STORAGE_TENANT_ID", "AZURE_STORAGE_CLIENT_ID", "AZURE_STORAGE_CLIENT_SECRET"],
)
@pytest.mark.asyncio
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()
@pytest.mark.asyncio
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()
file_system_client = MagicMock()
file_system_client.get_file_client = MagicMock(return_value=file_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.asyncio
async 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}):
logger = AzureBlobStorageLogger()
await logger.get_service_client()
assert (
fake_aio_module.DataLakeServiceClient.call_args.kwargs["account_url"]
== "https://test-account.dfs.core.windows.net"
)
def _fake_datalake_module() -> MagicMock:
fake_aio_module = MagicMock()
fake_aio_module.DataLakeServiceClient.side_effect = lambda **_: MagicMock(close=AsyncMock())
return fake_aio_module
@pytest.mark.asyncio
async def test_service_client_is_reused_until_its_ttl_elapses(mock_env_vars):
"""Within the TTL every upload must share one live client; closing a client
that is still in use by a concurrent upload fails that upload with an Azure
AuthenticationFailed error and drops the audit record"""
fake_aio_module = _fake_datalake_module()
now = 1_000_000.0
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger(clock=lambda: now)
first = await logger.get_service_client()
second = await logger.get_service_client()
assert second is first, "a second call inside the TTL must return the same client"
first.close.assert_not_awaited()
assert fake_aio_module.DataLakeServiceClient.call_count == 1
@pytest.mark.asyncio
async def test_service_client_is_replaced_once_its_ttl_elapses(mock_env_vars):
fake_aio_module = _fake_datalake_module()
ticks = iter((1_000_000.0, 1_000_000.0 + _DEFAULT_TTL_FOR_HTTPX_CLIENTS + 1, 2_000_000.0))
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger(clock=lambda: next(ticks))
first = await logger.get_service_client()
second = await logger.get_service_client()
assert second is not first, "an expired client must be closed and rebuilt"
first.close.assert_awaited_once()
second.close.assert_not_awaited()
assert fake_aio_module.DataLakeServiceClient.call_count == 2
@pytest.mark.asyncio
async def test_service_client_is_replaced_at_the_exact_ttl_boundary(mock_env_vars):
fake_aio_module = _fake_datalake_module()
ticks = iter((1_000_000.0, 1_000_000.0 + _DEFAULT_TTL_FOR_HTTPX_CLIENTS, 2_000_000.0))
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger(clock=lambda: next(ticks))
first = await logger.get_service_client()
second = await logger.get_service_client()
assert second is not first, "a call exactly at the TTL must rebuild the client"
first.close.assert_awaited_once()
second.close.assert_not_awaited()
assert fake_aio_module.DataLakeServiceClient.call_count == 2
@pytest.mark.parametrize(
("payload_id", "expected"),
(
("resp_YWJj", "resp_YWJj.json"),
("resp_YWJjZA==", "resp_YWJjZA.json"),
("resp_YWJjZGU=", "resp_YWJjZGU.json"),
("resp_+/8=", "resp_+_8.json"),
("resp_a+b", "resp_a+b.json"),
("chatcmpl-abc123", "chatcmpl-abc123.json"),
),
)
def test_adls_safe_file_name_rewrites_base64_padding_and_reserved_characters(payload_id, expected):
name = adls_safe_file_name(payload_id)
assert name == expected, f"{payload_id!r} must map to {expected!r}, got {name!r}"
assert re.fullmatch(r"[A-Za-z0-9._+-]+\.json", name), (
f"{name!r} must contain no characters Data Lake treats as path separators or signing input"
)
def test_adls_safe_file_name_rewrites_only_responses_ids():
ids = ("svc/req-1", "svc_req-1", "trace=7", "trace7", "resp_YWJjZA==", "resp_+/8=")
names = {payload_id: adls_safe_file_name(payload_id) for payload_id in ids}
assert names == {
"svc/req-1": "svc/req-1.json",
"svc_req-1": "svc_req-1.json",
"trace=7": "trace=7.json",
"trace7": "trace7.json",
"resp_YWJjZA==": "resp_YWJjZA.json",
"resp_+/8=": "resp_+_8.json",
}, "caller-chosen ids must keep their own names so none overwrites another, while resp_ ids are rewritten"
def test_adls_safe_file_name_rewrites_ids_with_dot_or_empty_path_segments():
ids = (
"../other-filesystem/x",
"../2026-09-30/x",
"svc/../../x",
"%2e%2e/other-filesystem/x",
".%2E/x",
"a..b/c",
"../",
"svc/./x",
"./x",
"svc//x",
"/x",
"x/",
)
names = {payload_id: adls_safe_file_name(payload_id) for payload_id in ids}
assert names == {
"../other-filesystem/x": ".._other-filesystem_x.json",
"../2026-09-30/x": ".._2026-09-30_x.json",
"svc/../../x": "svc_.._.._x.json",
"%2e%2e/other-filesystem/x": "%2e%2e_other-filesystem_x.json",
".%2E/x": ".%2E_x.json",
"a..b/c": "a..b/c.json",
"../": ".._.json",
"svc/./x": "svc_._x.json",
"./x": "._x.json",
"svc//x": "svc__x.json",
"/x": "_x.json",
"x/": "x_.json",
}, "a dot or empty segment must never reach the Data Lake path, while ids without one keep their own names"
def test_adls_safe_file_name_is_deterministic_and_distinct_per_id():
ids = (
"resp_" + base64.b64encode(b"a").decode(),
"resp_" + base64.b64encode(b"ab").decode(),
"resp_" + base64.b64encode(b"abc").decode(),
"resp_" + base64.b64encode(b"abcd").decode(),
"resp_" + base64.b64encode(b"\xfb\xff").decode(),
)
names = tuple(adls_safe_file_name(payload_id) for payload_id in ids)
again = tuple(adls_safe_file_name(payload_id) for payload_id in ids)
assert names == again, "the rewrite must be deterministic for a given id"
assert len(set(names)) == len(ids), f"distinct ids must map to distinct names, got {names}"
def test_adls_safe_file_name_without_an_id_is_a_uuid_json():
name = adls_safe_file_name(None)
assert re.fullmatch(r"[0-9a-f-]{36}\.json", name), (
f"an id-less payload must fall back to a uuid-named file, got {name!r}"
)
@pytest.mark.asyncio
async def test_account_key_upload_names_the_file_adls_safe_and_keeps_the_original_id(
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()
file_system_client = MagicMock()
file_system_client.get_file_client = MagicMock(return_value=file_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)
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger()
await logger.async_upload_payload_to_azure_blob_storage({"id": "resp_YWJjZA=="})
file_system_client.get_file_client.assert_called_once_with(
f"{datetime.now().strftime('%Y-%m-%d')}/resp_YWJjZA.json"
)
body = json.loads(file_client.append_data.call_args.kwargs["data"])
assert body["id"] == "resp_YWJjZA==", "the stored payload must keep the original id byte for byte"
@pytest.mark.asyncio
async def test_entra_upload_names_the_file_adls_safe_and_keeps_the_original_id(mock_env_vars):
with (
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,
):
mock_http_client = AsyncMock()
mock_response = MagicMock()
mock_http_client.put.return_value = mock_response
mock_http_client.patch.return_value = mock_response
mock_get_client.return_value = mock_http_client
mock_token_provider = MagicMock()
mock_token_provider.return_value = "mock-azure-ad-token"
mock_get_token.return_value = mock_token_provider
logger = AzureBlobStorageLogger()
logger.azure_auth_token = "mock-azure-ad-token"
logger.token_expiry = None
await logger.async_upload_payload_to_azure_blob_storage({"id": "resp_YWJjZA=="})
put_call_args = mock_http_client.put.call_args
assert put_call_args[0][0] == (
"https://test-account.dfs.core.windows.net/test-container/resp_YWJjZA.json?resource=file"
), f"the Entra path must be the rewritten name, got {put_call_args[0][0]!r}"
append_call = mock_http_client.patch.call_args_list[0]
assert "resp_YWJjZA==" in append_call[1]["data"], "the stored payload must keep the original id byte for byte"
class _FrozenDatetime(datetime):
@classmethod
def now(cls, tz=None):
instant = datetime(2026, 9, 30, 3, 5, 9, tzinfo=timezone.utc)
if tz is None:
return instant.astimezone(timezone(timedelta(hours=-7))).replace(tzinfo=None)
return instant.astimezone(tz)
def _key_created_audit_log(audit_log_id: str) -> StandardAuditLogPayload:
return StandardAuditLogPayload(
id=audit_log_id,
updated_at="2026-09-30T03:05:09+00:00",
changed_by="admin-user",
changed_by_api_key="hashed-admin-key",
action="created",
table_name="LiteLLM_VerificationToken",
object_id="hashed-new-key",
before_value=None,
updated_values=json.dumps({"key_alias": "audit-key"}),
)
@pytest.mark.asyncio
async def test_audit_log_is_uploaded_to_a_dated_audit_logs_path_with_a_service_principal(mock_env_vars, monkeypatch):
monkeypatch.setattr(azure_storage_module, "datetime", _FrozenDatetime)
audit_log = _key_created_audit_log("audit-id-sp")
with patch( # test-quality-ok: REST client is created inside the method; assert emitted requests
"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()
logger.azure_auth_token = "sp-token"
logger.token_expiry = datetime(2026, 9, 30, 9, 30)
await logger.async_log_audit_log_event(audit_log)
file_url = (
"https://test-account.dfs.core.windows.net/test-container/audit_logs/2026-09-30/03-05-09_audit-id-sp.json"
)
assert [call.args[0] for call in mock_http_client.put.call_args_list] == [f"{file_url}?resource=file"]
append_call, flush_call = mock_http_client.patch.call_args_list
assert append_call.args[0] == f"{file_url}?action=append&position=0"
assert json.loads(append_call.kwargs["data"]) == audit_log
assert flush_call.args[0] == f"{file_url}?action=flush&position={len(append_call.kwargs['data'].encode())}"
assert logger.log_queue == [], "audit logs must not be mixed into the request log queue"
@pytest.mark.asyncio
async def test_audit_log_is_uploaded_to_a_dated_audit_logs_path_with_an_account_key(mock_env_vars, monkeypatch):
monkeypatch.setenv("AZURE_STORAGE_ACCOUNT_KEY", "dGVzdC1rZXk=")
monkeypatch.setattr(azure_storage_module, "datetime", _FrozenDatetime)
audit_log = _key_created_audit_log("audit-id-key")
file_client = MagicMock()
file_client.create_file = AsyncMock()
file_client.append_data = AsyncMock()
file_client.flush_data = AsyncMock()
file_system_client = MagicMock()
file_system_client.get_file_client = MagicMock(return_value=file_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)
with patch.dict(sys.modules, {"azure.storage.filedatalake.aio": fake_aio_module}):
logger = AzureBlobStorageLogger()
await logger.async_log_audit_log_event(audit_log)
service_client.get_file_system_client.assert_called_once_with(file_system="test-container")
file_system_client.get_file_client.assert_called_once_with("audit_logs/2026-09-30/03-05-09_audit-id-key.json")
file_client.create_file.assert_awaited_once_with()
uploaded = file_client.append_data.await_args.kwargs["data"]
assert json.loads(uploaded) == audit_log
assert file_client.append_data.await_args.kwargs == {"data": uploaded, "offset": 0, "length": len(uploaded)}
file_client.flush_data.assert_awaited_once_with(position=len(uploaded), offset=0)