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
Merge litellm_internal_staging into litellm_fix_raw_key_log_persistence
Mateo Wang2f40eb5d93af
diff --cc litellm/proxy/spend_tracking/spend_tracking_utils.pyindex e8aa2325a18,0b56f0d8246..4592add1032--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py@@@ -56,7 -53,14 +54,7 @@@ def _get_max_string_length_prompt_in_dbreturn DEFAULT_MAX_STRING_LENGTH_PROMPT_IN_DB- def _is_master_key(api_key: Optional[str], _master_key: Optional[str]) -> bool:-def _hash_api_key_for_spend_log(api_key: str) -> str:- stripped: Final = api_key[7:] if api_key[:7].lower() == "bearer " else api_key- if stripped.startswith("sk-"):- return hash_token(stripped)- return stripped--+ def _is_master_key(api_key: str | None, _master_key: str | None) -> bool:"""Raw-only constant-time master-key comparison. The hashed form is neverconsidered equivalent — only the raw master-key string matches.@@@ -66,38 -70,19 +64,35 @@@return secrets.compare_digest(api_key, _master_key)+_HASHED_JWT_RE = re.compile(r"^hashed-jwt-[a-fA-F0-9]{64}$")++- def _redact_logged_api_key(- value: str | None, *, already_hashed: bool = False- ) -> str | None:++def _redact_logged_api_key(value: str | None, *, already_hashed: bool = False) -> str | None:+ if not isinstance(value, str) or not value:+ return None- stripped = re.sub(r"(?i)^bearer ", "", value)++ stripped: Final = re.sub(r"(?i)^bearer ", "", value)+ if not stripped:+ return None+ if already_hashed and is_valid_sha256_hash(stripped):+ return stripped+ if _HASHED_JWT_RE.match(stripped):+ return stripped+ return hash_token(stripped)++def _get_spend_logs_metadata(- metadata: Optional[dict],- applied_guardrails: Optional[List[str]] = None,- batch_models: Optional[List[str]] = None,- mcp_tool_call_metadata: Optional[StandardLoggingMCPToolCall] = None,- vector_store_request_metadata: Optional[- List[StandardLoggingVectorStoreRequest]- ] = None,- guardrail_information: Optional[List[StandardLoggingGuardrailInformation]] = None,- usage_object: Optional[dict] = None,- model_map_information: Optional[StandardLoggingModelInformation] = None,- cold_storage_object_key: Optional[str] = None,- litellm_overhead_time_ms: Optional[float] = None,- cost_breakdown: Optional[CostBreakdown] = None,+ metadata: dict | None,+ applied_guardrails: list[str] | None = None,+ batch_models: list[str] | None = None,+ mcp_tool_call_metadata: StandardLoggingMCPToolCall | None = None,+ vector_store_request_metadata: list[StandardLoggingVectorStoreRequest] | None = None,+ guardrail_information: list[StandardLoggingGuardrailInformation] | None = None,+ usage_object: dict | None = None,+ model_map_information: StandardLoggingModelInformation | None = None,+ cold_storage_object_key: str | None = None,+ litellm_overhead_time_ms: float | None = None,+ cost_breakdown: CostBreakdown | None = None,+ litellm_call_id: str | None = None,) -> SpendLogsMetadata:if metadata is None:return SpendLogsMetadata(@@@ -135,21 -122,10 +132,13 @@@)# Filter the metadata dictionary to include only the specified keys- clean_metadata = SpendLogsMetadata(- **{ # type: ignore- key: metadata.get(key) for key in SpendLogsMetadata.__annotations__.keys()- }- )- _raw_key = clean_metadata.get("user_api_key")- _trusted_hash = metadata.get("user_api_key_hash") if metadata else None- _already_hashed = (- isinstance(_trusted_hash, str)- and is_valid_sha256_hash(_trusted_hash)- and _trusted_hash == _raw_key- )- clean_metadata["user_api_key"] = _redact_logged_api_key(- _raw_key, already_hashed=_already_hashed+ clean_metadata: Final = SpendLogsMetadata(**{key: metadata.get(key) for key in SpendLogsMetadata.__annotations__})- raw_user_api_key: Final = clean_metadata.get("user_api_key")- if raw_user_api_key is not None and isinstance(raw_user_api_key, str):- clean_metadata["user_api_key"] = _hash_api_key_for_spend_log(raw_user_api_key)++ _raw_key: Final = clean_metadata.get("user_api_key")++ _trusted_hash: Final = metadata.get("user_api_key_hash")++ _already_hashed: Final = (++ isinstance(_trusted_hash, str) and is_valid_sha256_hash(_trusted_hash) and _trusted_hash == _raw_key+ )++ clean_metadata["user_api_key"] = _redact_logged_api_key(_raw_key, already_hashed=_already_hashed)clean_metadata["applied_guardrails"] = applied_guardrailsclean_metadata["batch_models"] = batch_modelsclean_metadata["mcp_tool_call_metadata"] = mcp_tool_call_metadata@@@ -305,40 -278,22 +291,29 @@@ def get_logging_payload(kwargs, responsstandard_logging_completion_tokens: int = 0standard_logging_total_tokens: int = 0if standard_logging_payload is not None:- standard_logging_prompt_tokens = standard_logging_payload.get(- "prompt_tokens", 0- )- standard_logging_completion_tokens = standard_logging_payload.get(- "completion_tokens", 0- )+ standard_logging_prompt_tokens = standard_logging_payload.get("prompt_tokens", 0)+ standard_logging_completion_tokens = standard_logging_payload.get("completion_tokens", 0)standard_logging_total_tokens = standard_logging_payload.get("total_tokens", 0)- _trusted_hash = metadata.get("user_api_key_hash") if metadata else None- if api_key is not None and isinstance(api_key, str):- api_key = _hash_api_key_for_spend_log(api_key)++ _trusted_hash = metadata.get("user_api_key_hash")+ _key_already_hashed = (- isinstance(_trusted_hash, str)- and is_valid_sha256_hash(_trusted_hash)- and _trusted_hash == api_key++ isinstance(_trusted_hash, str) and is_valid_sha256_hash(_trusted_hash) and _trusted_hash == api_key+ )+ api_key = _redact_logged_api_key(api_key, already_hashed=_key_already_hashed) or ""if (standard_logging_payload is not None): # [TODO] migrate completely to sl payload. currently missing pass-through endpoint data- api_key = api_key or standard_logging_payload["metadata"].get("user_api_key_hash") or ""+ api_key = (+ api_key- or standard_logging_payload["metadata"].get("user_api_key_hash")++ or _redact_logged_api_key(++ standard_logging_payload["metadata"].get("user_api_key_hash"), already_hashed=True++ )+ or ""+ )- end_user_id = end_user_id or standard_logging_payload["metadata"].get(- "user_api_key_end_user_id"- )- request_tags = (- safe_dumps(metadata.get("tags", []))- if isinstance(metadata.get("tags", []), list)- else "[]"- )+ end_user_id = end_user_id or standard_logging_payload["metadata"].get("user_api_key_end_user_id")- # BUG FIX: Don't overwrite api_key when standard_logging_payload is None- # The api_key was already extracted from metadata (line 243) and hashed (lines 256-259)+ request_tags = safe_dumps(metadata.get("tags", [])) if isinstance(metadata.get("tags", []), list) else "[]"if (- standard_logging_payload is not None- and standard_logging_payload.get("request_tags") is not None+ standard_logging_payload is not None and standard_logging_payload.get("request_tags") is not None): # use 'tags' from standard logging payload insteadrequest_tags = safe_dumps(standard_logging_payload["request_tags"])diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pyindex 67d57d2d6bb,9710dc44e99..706466d5033--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py@@@ -4,9 -4,10 +4,9 @@@ import jsoimport osimport sysfrom datetime import timezone- from typing import Any, cast+ from typing import Any, Final, castimport pytest-from fastapi.testclient import TestClientsys.path.insert(0, os.path.abspath("../../../..")@@@ -27,15 -29,16 +28,17 @@@ from litellm.proxy.spend_tracking.spend_get_response_for_spend_logs_payload,_get_spend_logs_metadata,_get_vector_store_request_for_spend_logs_payload,- _hash_api_key_for_spend_log,_is_master_key,+ _redact_logged_api_key,_redact_prompt_leaks_in_error_string,_sanitize_error_information_for_spend_logs,+ _sanitize_guardrail_information_for_spend_logs,_sanitize_request_body_for_spend_logs_payload,_should_store_prompts_and_responses_in_spend_logs,get_logging_payload,+ get_spend_logs_id,)+from litellm.proxy.utils import hash_tokenfrom litellm.types.utils import (StandardLoggingHiddenParams,StandardLoggingMetadata,@@@ -2061,253 -2591,653 +2577,920 @@@ def test_sanitize_error_information_redassert REDACTED_BY_LITELM_STRING in sanitized["error_message"]+# ── _redact_logged_api_key unit tests ──────────────────────────────────────+++def test_redact_logged_api_key_none_returns_none():+ assert _redact_logged_api_key(None) is None+++def test_redact_logged_api_key_empty_string_returns_none():+ assert _redact_logged_api_key("") is None+++def test_redact_logged_api_key_sk_key_is_hashed():+ raw = "sk-1234secret"+ result = _redact_logged_api_key(raw)+ assert result == hash_token(raw)+ assert result is not None+ assert not result.startswith("sk-")+ assert len(result) == 64+++def test_redact_logged_api_key_bearer_sk_equals_sk_hash():+ raw = "sk-1234secret"+ result_plain = _redact_logged_api_key(raw)+ result_bearer = _redact_logged_api_key(f"Bearer {raw}")+ assert result_bearer == result_plain+++def test_redact_logged_api_key_bearer_case_insensitive():+ raw = "sk-1234secret"+ result_lower = _redact_logged_api_key(f"bearer {raw}")+ result_upper = _redact_logged_api_key(f"BEARER {raw}")+ expected = hash_token(raw)+ assert result_lower == expected+ assert result_upper == expected+++def test_redact_logged_api_key_non_sk_raw_key_is_hashed():+ raw = "anthropic-raw-key-xyz"+ result = _redact_logged_api_key(raw)+ assert result is not None+ assert result != raw+ assert len(result) == 64+ assert result == hash_token(raw)+++def test_redact_logged_api_key_already_valid_sha256_passes_through_with_flag():+ already_hashed = hash_token("sk-some-key")+ assert len(already_hashed) == 64+ result = _redact_logged_api_key(already_hashed, already_hashed=True)+ assert result == already_hashed+ assert hash_token(already_hashed) != result # no double-hash+++def test_redact_logged_api_key_sha256_without_flag_is_hashed():+ already_hashed = hash_token("sk-some-key")+ assert len(already_hashed) == 64+ result = _redact_logged_api_key(already_hashed)+ assert result is not None+ assert result != already_hashed+ assert len(result) == 64+ assert result == hash_token(already_hashed)++++def test_redact_logged_api_key_long_opaque_token_is_hashed():++ raw = "x1" * 450++ assert len(raw) == 900++ result = _redact_logged_api_key(raw)++ assert result is not None++ assert result != raw++ assert raw not in result++ assert len(result) == 64++ assert result == hash_token(raw)+++++def test_redact_logged_api_key_hashed_jwt_passes_through():+ jwt_hash = "hashed-jwt-" + "a" * 64+ result = _redact_logged_api_key(jwt_hash)+ assert result == jwt_hash+++def test_redact_logged_api_key_hashed_jwt_short_suffix_is_hashed():+ short_jwt = "hashed-jwt-tooshort"+ result = _redact_logged_api_key(short_jwt)+ assert result is not None+ assert result != short_jwt+ assert len(result) == 64+ assert result == hash_token(short_jwt)+++def test_redact_logged_api_key_bearer_only_returns_none():+ # "bearer " with nothing after stripping is equivalent to no key+ assert _redact_logged_api_key("bearer ") is None+ assert _redact_logged_api_key("Bearer ") is None+ assert _redact_logged_api_key("BEARER ") is None+++# ── _get_spend_logs_metadata key-hash invariant tests ─────────────────────+++def test_get_spend_logs_metadata_sk_key_hashed():+ raw = "sk-1234secret"+ meta = _get_spend_logs_metadata({"user_api_key": raw})+ assert meta["user_api_key"] == hash_token(raw)+ assert meta["user_api_key"] is not None+ result = meta["user_api_key"]+ assert result is not None+ assert not result.startswith("sk-")+ assert len(result) == 64+++def test_get_spend_logs_metadata_bearer_sk_key_hashed_same_as_plain():+ raw = "sk-1234secret"+ meta_plain = _get_spend_logs_metadata({"user_api_key": raw})+ meta_bearer = _get_spend_logs_metadata({"user_api_key": f"Bearer {raw}"})+ assert meta_bearer["user_api_key"] == meta_plain["user_api_key"]+++def test_get_spend_logs_metadata_non_sk_raw_key_hashed():+ raw = "anthropic-raw-key-xyz"+ meta = _get_spend_logs_metadata({"user_api_key": raw})+ result = meta["user_api_key"]+ assert result is not None+ assert result != raw+ assert len(result) == 64+++def test_get_spend_logs_metadata_already_hashed_unchanged_with_provenance():+ already_hashed = hash_token("sk-some-key")+ meta = _get_spend_logs_metadata(+ {"user_api_key": already_hashed, "user_api_key_hash": already_hashed}+ )+ assert meta["user_api_key"] == already_hashed+ assert hash_token(already_hashed) != meta["user_api_key"] # no double-hash+++def test_get_spend_logs_metadata_already_hashed_no_provenance_is_rehashed():+ already_hashed = hash_token("sk-some-key")+ meta = _get_spend_logs_metadata({"user_api_key": already_hashed})+ assert meta["user_api_key"] != already_hashed+ assert meta["user_api_key"] == hash_token(already_hashed)+++def test_get_spend_logs_metadata_provenance_bypass_requires_hash_match():+ already_hashed = hash_token("sk-some-key")+ different_hash = hash_token("sk-other-key")+ meta = _get_spend_logs_metadata(+ {"user_api_key": already_hashed, "user_api_key_hash": different_hash}+ )+ assert meta["user_api_key"] == hash_token(already_hashed)+++def test_get_spend_logs_metadata_hashed_jwt_unchanged():+ jwt_hash = "hashed-jwt-" + "b" * 64+ meta = _get_spend_logs_metadata({"user_api_key": jwt_hash})+ assert meta["user_api_key"] == jwt_hash+++def test_get_spend_logs_metadata_none_key_is_none():+ meta = _get_spend_logs_metadata({"user_api_key": None})+ assert meta["user_api_key"] is None+++# ── get_logging_payload key-hash invariant tests ───────────────────────────+++ def test_get_logging_payload_uses_recovered_combined_usage_on_failure():+ """A request that fails mid-stream has no usable response_obj usage, but the+ streaming handler recovers the usage from the chunks already delivered and+ the failure hook surfaces it as ``combined_usage_object``. The spend-log+ payload must record those token counts instead of zero.+ """+ from litellm.types.utils import Usage++ kwargs = {+ "model": "anthropic/claude-haiku-4-5",+ "call_type": "acompletion",+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ "combined_usage_object": Usage(+ prompt_tokens=30, completion_tokens=1, total_tokens=31+ ),+ }+ response_obj = Exception("MidStreamFallbackError: read timeout")+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )++ assert payload["prompt_tokens"] == 30+ assert payload["completion_tokens"] == 1+ assert payload["total_tokens"] == 31+++ def test_get_logging_payload_failure_without_recovered_usage_is_zero():+ """A failure with no recovered usage keeps zero token counts, so the+ combined-usage override never invents tokens for ordinary failures.+ """+ kwargs = {+ "model": "anthropic/claude-haiku-4-5",+ "call_type": "acompletion",+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ }+ response_obj = Exception("BadRequestError")+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )++ assert payload["total_tokens"] == 0+++ def test_get_logging_payload_sets_litellm_call_id_for_correlation():+ """LIT-3868: a successful spend log must carry the x-litellm-call-id (the+ trace id) in its metadata, distinct from request_id, which stays the+ provider response id. Without this there is no way to correlate a DB row+ with its trace for a successful call.+ """+ provider_response_id = "chatcmpl-e6e6f3e9-c392-404e-9a71-5361c79d8470"+ trace_call_id = "c6a77556-19ce-4406-b287-53f5fb4b2b55"++ kwargs = {+ "model": "openai/gpt-4o-mini",+ "call_type": "acompletion",+ "litellm_call_id": trace_call_id,+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ }+ response_obj = {+ "id": provider_response_id,+ "usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},+ }+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )+ metadata = json.loads(payload["metadata"])++ assert payload["request_id"] == provider_response_id+ assert metadata["litellm_call_id"] == trace_call_id+ assert metadata["litellm_call_id"] != payload["request_id"]+++ def test_get_logging_payload_litellm_call_id_falls_back_to_litellm_params():+ """litellm_call_id may only be present in litellm_params; it must still land+ in the spend log metadata so correlation works on that path too.+ """+ trace_call_id = "fallback-7a1c-42d9-9f0e-2b6c5d4e3f21"+ kwargs = {+ "model": "openai/gpt-4o-mini",+ "call_type": "acompletion",+ "litellm_params": {+ "litellm_call_id": trace_call_id,+ "metadata": {"user_api_key": "sk-test"},+ },+ }+ response_obj = {+ "id": "chatcmpl-abc123",+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )++ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id+++ def test_get_logging_payload_litellm_call_id_when_response_has_no_id():+ """When the provider returns no id, request_id falls back to the call id, so+ request_id and the metadata call id hold the same value and correlation+ still resolves.+ """+ trace_call_id = "noid-5b2e-4c7a-9d10-3f8a1c2b4e6d"+ kwargs = {+ "model": "openai/gpt-4o-mini",+ "call_type": "acompletion",+ "litellm_call_id": trace_call_id,+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ }+ response_obj = {+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}+ }+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )++ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id+ assert payload["request_id"] == trace_call_id+++ def test_get_logging_payload_cache_hit_keeps_raw_litellm_call_id():+ """On a cache hit request_id is suffixed to stay unique, but the metadata+ litellm_call_id stays the raw trace id so the row still points at its trace.+ """+ trace_call_id = "cache-9a1c-42d9-9f0e-2b6c5d4e3f21"+ kwargs = {+ "model": "openai/gpt-4o-mini",+ "call_type": "acompletion",+ "litellm_call_id": trace_call_id,+ "cache_hit": True,+ "litellm_params": {"metadata": {"user_api_key": "sk-test"}},+ }+ response_obj = {+ "id": "chatcmpl-cache-src",+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ }+ now = datetime.datetime.now(timezone.utc)++ payload = get_logging_payload(+ kwargs=kwargs, response_obj=response_obj, start_time=now, end_time=now+ )++ assert json.loads(payload["metadata"])["litellm_call_id"] == trace_call_id+ assert "_cache_hit" in payload["request_id"]+ assert json.loads(payload["metadata"])["litellm_call_id"] != payload["request_id"]++-class TestHashApiKeyForSpendLog:++class TestSpendLogKeyRedaction:+ """Regression: plaintext API keys with Bearer prefix were stored in+ SpendLogs for failed requests (LIT-4121)"""++ def test_bearer_prefixed_sk_key_is_hashed(self):+ raw = "Bearer sk-WLi4iRn4JmbVlTaYw12IOA"- result = _hash_api_key_for_spend_log(raw)++ result = _redact_logged_api_key(raw)++ assert result is not None+ assert not result.startswith("Bearer")+ assert not result.startswith("sk-")+ assert len(result) == 64++ def test_bare_sk_key_is_hashed(self):+ raw = "sk-WLi4iRn4JmbVlTaYw12IOA"- result = _hash_api_key_for_spend_log(raw)++ result = _redact_logged_api_key(raw)++ assert result is not None+ assert not result.startswith("sk-")+ assert len(result) == 64++ def test_bearer_lowercase_is_handled(self):+ raw = "bearer sk-WLi4iRn4JmbVlTaYw12IOA"- result = _hash_api_key_for_spend_log(raw)++ result = _redact_logged_api_key(raw)++ assert result is not None+ assert not result.startswith("bearer")+ assert not result.startswith("sk-")+ assert len(result) == 64++ def test_already_hashed_key_unchanged(self):+ hashed = "bcfe8173f5447f10be0e7fb37aaa8b97829d5c9e0498232152f9d123456789ab"- assert _hash_api_key_for_spend_log(hashed) == hashed++ assert _redact_logged_api_key(hashed) == hashed+- def test_bearer_prefixed_non_sk_key_strips_prefix(self):++ def test_bearer_prefixed_non_sk_key_is_hashed(self):+ raw = "Bearer some-other-token-format"- result = _hash_api_key_for_spend_log(raw)- assert result == "some-other-token-format"++ result = _redact_logged_api_key(raw)++ assert result == hash_token("some-other-token-format")++ assert result is not None+ assert not result.startswith("Bearer")++ def test_bearer_and_bare_produce_same_hash(self):+ bare = "sk-WLi4iRn4JmbVlTaYw12IOA"+ bearer = "Bearer sk-WLi4iRn4JmbVlTaYw12IOA"- assert _hash_api_key_for_spend_log(bare) == _hash_api_key_for_spend_log(bearer)++ assert _redact_logged_api_key(bare) == _redact_logged_api_key(bearer)+++++@patch("litellm.proxy.proxy_server.master_key", None)+@patch("litellm.proxy.proxy_server.general_settings", {})+def test_get_logging_payload_non_sk_raw_key_both_fields_hashed():+ raw = "anthropic-raw-key-xyz"+ kwargs = {+ "model": "openai/gpt-4.1",+ "messages": [{"role": "user", "content": "Hello"}],+ "call_type": "acompletion",+ "litellm_params": {+ "metadata": {+ "user_api_key": raw,+ "user_api_key_user_id": "test_user",+ "user_api_key_team_id": "test_team",+ }+ },+ }+ payload = get_logging_payload(+ kwargs=kwargs,+ response_obj=Exception("error"),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )++ assert payload["api_key"] != raw+ assert len(payload["api_key"]) == 64++ parsed_meta = json.loads(payload["metadata"])+ assert parsed_meta["user_api_key"] != raw+ assert parsed_meta["user_api_key"] is not None+ assert len(parsed_meta["user_api_key"]) == 64+ @patch("litellm.proxy.proxy_server.master_key", None)+ @patch("litellm.proxy.proxy_server.general_settings", {})+ def test_get_logging_payload_hashes_bearer_prefixed_api_key():+ """Regression for LIT-4121: failed-request spend logs stored plaintext+ 'Bearer sk-...' in both the api_key column and metadata.user_api_key"""+ raw_key = "Bearer sk-WLi4iRn4JmbVlTaYw12IOA"++ kwargs = {+ "model": "openai/gpt-4.1",+ "call_type": "acompletion",+ "litellm_params": {+ "metadata": {+ "user_api_key": raw_key,+ "user_api_key_user_id": "test_user",+ "user_api_key_team_id": "test_team",+ "status": "failure",+ }+ },+ }++ payload = get_logging_payload(+ kwargs=kwargs,+ response_obj=Exception("model error"),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )++ assert not payload["api_key"].startswith("Bearer"), (+ f"api_key column contains plaintext Bearer key: {payload['api_key']}"+ )+ assert not payload["api_key"].startswith("sk-"), (+ f"api_key column contains unhashed key: {payload['api_key']}"+ )++ metadata_dict = json.loads(payload["metadata"])+ assert not metadata_dict["user_api_key"].startswith("Bearer"), (+ f"metadata user_api_key contains plaintext Bearer key: {metadata_dict['user_api_key']}"+ )+ assert not metadata_dict["user_api_key"].startswith("sk-"), (+ f"metadata user_api_key contains unhashed key: {metadata_dict['user_api_key']}"+ )+++ @patch("litellm.proxy.spend_tracking.spend_tracking_utils._should_store_prompts_and_responses_in_spend_logs")+ def test_sanitize_guardrail_information_preserves_headroom_compression_token_stats(+ mock_should_store,+ ):+ """+ Headroom's compression stats live in guardrail_response, which is redacted+ by default. Purely numeric token stats carry no prompt content and must+ survive so daily spend aggregation can count compression_saved_tokens;+ everything else in guardrail_response stays redacted.+ """+ mock_should_store.return_value = False+ guardrail_info = [+ {+ "guardrail_name": "headroom-compressor",+ "guardrail_provider": "headroom",+ "guardrail_status": "success",+ "guardrail_response": {+ "tokens_before": 1000,+ "tokens_after": 400,+ "tokens_saved": 600,+ "compression_ratio": 0.4,+ "transforms_applied": ["dedupe_messages"],+ },+ },+ {+ "guardrail_name": "echo-guard",+ "guardrail_status": "success",+ "guardrail_response": {+ "evaluated_input": "secret prompt",+ "tokens_saved": "prompt text hiding in a stat key",+ },+ },+ ]++ result = _sanitize_guardrail_information_for_spend_logs(guardrail_info)++ assert result is not None+ assert result[0]["guardrail_response"] == {+ "tokens_before": 1000,+ "tokens_after": 400,+ "tokens_saved": 600,+ "compression_ratio": 0.4,+ }+ assert result[1]["guardrail_response"] == REDACTED_BY_LITELM_STRING+++ @pytest.mark.asyncio+ async def test_compression_savings_survive_to_spend_log_payload_metadata(monkeypatch):+ """+ End-to-end seam test for the native compression write path on+ /v1/messages: the pre-call deployment hook records savings into the call+ kwargs' litellm_metadata, the logging object captures it via+ update_from_kwargs (exactly as llm_http_handler does for+ anthropic_messages), and get_logging_payload lands it in+ SpendLogsPayload.metadata JSON under ``compression_savings``.+ """+ from litellm.integrations.compression_interception.handler import (+ CompressionInterceptionLogger,+ )+ from litellm.litellm_core_utils.litellm_logging import Logging+ from litellm.types.utils import CallTypes++ monkeypatch.setattr(+ "litellm.integrations.compression_interception.handler.compress",+ lambda **kwargs: {+ "messages": [{"role": "user", "content": "compressed"}],+ "original_tokens": 12000,+ "compressed_tokens": 5000,+ "cache": {"auth.py": "content"},+ "tools": [],+ },+ )+ logger = CompressionInterceptionLogger()++ call_kwargs = {+ "model": "claude-sonnet-5",+ "messages": [{"role": "user", "content": "big context"}],+ "max_tokens": 512,+ "litellm_call_id": "test-compression-call-id",+ "litellm_metadata": {+ "user_api_key": "88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",+ "user_api_key_user_id": "u1",+ "user_api_key_team_id": "t1",+ },+ }+ hooked = await logger.async_pre_call_deployment_hook(kwargs=call_kwargs, call_type=CallTypes.anthropic_messages)+ assert hooked is not None++ start_time = datetime.datetime.now(timezone.utc)+ logging_obj = Logging(+ model="claude-sonnet-5",+ messages=hooked["messages"],+ stream=False,+ call_type="anthropic_messages",+ start_time=start_time,+ litellm_call_id="test-compression-call-id",+ function_id="test",+ )+ logging_obj.update_from_kwargs(+ kwargs=hooked,+ model="claude-sonnet-5",+ optional_params={"max_tokens": 512},+ litellm_params={+ "preset_cache_key": None,+ "stream_response": {},+ "model_info": hooked.get("model_info"),+ },+ custom_llm_provider="anthropic",+ )++ end_time = datetime.datetime.now(timezone.utc)+ logging_obj.model_call_details["completion_start_time"] = end_time+ payload = get_logging_payload(+ kwargs=logging_obj.model_call_details,+ response_obj={+ "id": "msg_test",+ "usage": {"prompt_tokens": 5000, "completion_tokens": 10, "total_tokens": 5010},+ },+ start_time=start_time,+ end_time=end_time,+ )++ payload_metadata = json.loads(payload["metadata"])+ assert payload_metadata["compression_savings"] == {+ "tokens_before": 12000,+ "tokens_after": 5000,+ "tokens_saved": 7000,+ "source": "compression_interception",+ }+++ def test_no_routing_decision_key_defaults_to_none_in_spend_log_metadata():+ payload = get_logging_payload(+ kwargs={+ "model": "gpt-4o-mini",+ "litellm_params": {"metadata": {"user_api_key": "test-key"}},+ },+ response_obj=litellm.ModelResponse(id="chatcmpl-no-routing-decision", choices=[], usage=litellm.Usage()),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ metadata = json.loads(payload["metadata"])+ assert metadata["routing_decision"] is None+++ @pytest.mark.parametrize("bucket", ["metadata", "litellm_metadata"])+ def test_internal_call_origin_survives_into_spend_log_metadata(bucket):+ """The origin is only useful if it reaches the row the Logs UI reads.++ _get_spend_logs_metadata projects onto SpendLogsMetadata.__annotations__, so an+ undeclared key is dropped silently. Both buckets are covered because the resolver+ returns litellm_metadata when present and metadata otherwise, and the classifier+ sub-call populates whichever the parent route used.+ """+ payload = get_logging_payload(+ kwargs={+ "model": "gpt-4o-mini",+ "litellm_params": {+ bucket: {+ "user_api_key": "test-key",+ "internal_call_origin": "autorouter_classifier",+ }+ },+ },+ response_obj=litellm.ModelResponse(id="chatcmpl-classifier", choices=[], usage=litellm.Usage()),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ metadata = json.loads(payload["metadata"])+ assert metadata["internal_call_origin"] == "autorouter_classifier"+++ def test_user_traffic_carries_no_internal_call_origin():+ """The negative class the badge depends on: an ordinary request must be+ distinguishable from a classifier call, not merely unlabelled by accident."""+ payload = get_logging_payload(+ kwargs={+ "model": "gpt-4o-mini",+ "litellm_params": {"metadata": {"user_api_key": "test-key"}},+ },+ response_obj=litellm.ModelResponse(id="chatcmpl-user-traffic", choices=[], usage=litellm.Usage()),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ metadata = json.loads(payload["metadata"])+ assert metadata["internal_call_origin"] is None+++ REDACTED_RESPONSE_PLACEHOLDER: Final = {"text": "redacted-by-litellm"}+ CONSTANT_ID_FROM_HASHED_PLACEHOLDER: Final = "00fcbef15a3b0097e14b0ca016ed30a0"+++ @pytest.mark.parametrize("call_type", ["aretrieve_batch", "acreate_file"])+ def test_get_spend_logs_id_stays_unique_when_the_response_is_a_redaction_placeholder(call_type):+ """request_id is the LiteLLM_SpendLogs primary key and the flush inserts with+ skip_duplicates, so two calls must never derive the same id from identical response+ content. Message redaction replaces every body it cannot redact with one fixed+ placeholder, which is what a batch and a file body both become, so hashing the+ response collapsed all of them onto a single id and silently dropped every row+ after the first."""+ suffix = "_batch_cost" if call_type == "aretrieve_batch" else ""+ first = get_spend_logs_id(call_type, dict(REDACTED_RESPONSE_PLACEHOLDER), {"litellm_call_id": "call-id-1"})+ second = get_spend_logs_id(call_type, dict(REDACTED_RESPONSE_PLACEHOLDER), {"litellm_call_id": "call-id-2"})++ assert first == f"call-id-1{suffix}"+ assert second == f"call-id-2{suffix}"+ assert first != second+ assert first != CONSTANT_ID_FROM_HASHED_PLACEHOLDER+ assert second != CONSTANT_ID_FROM_HASHED_PLACEHOLDER+++ @pytest.mark.parametrize("call_type", ["aretrieve_batch", "acreate_file"])+ def test_get_spend_logs_id_prefers_the_response_id_for_batch_and_file_calls(call_type):+ """A batch or file response that survives redaction carries its own id, so the row+ keys off that rather than the per-call id."""+ expected = "batch_abc123_batch_cost" if call_type == "aretrieve_batch" else "batch_abc123"+ assert get_spend_logs_id(call_type, {"id": "batch_abc123"}, {"litellm_call_id": "call-id-1"}) == expected+++ def test_get_logging_payload_gives_redacted_batch_and_file_rows_distinct_request_ids():+ """End to end at the payload level: a batch retrieve and a file create whose bodies+ were both flattened to the same redaction placeholder must still produce two+ insertable rows, each carrying its own spend."""+ payloads = [+ get_logging_payload(+ kwargs={+ "call_type": call_type,+ "model": model,+ "litellm_call_id": call_id,+ "litellm_params": {"metadata": {"user_api_key": "test-key"}},+ },+ response_obj=dict(REDACTED_RESPONSE_PLACEHOLDER),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ for call_type, model, call_id in (+ ("aretrieve_batch", "global.anthropic.claude-haiku-4-5-20251001-v1:0", "call-id-batch"),+ ("acreate_file", "vertex_ai/gemini-2.5-flash", "call-id-file"),+ )+ ]+ request_ids = [payload["request_id"] for payload in payloads]++ assert request_ids == ["call-id-batch_batch_cost", "call-id-file"]+ assert len(set(request_ids)) == len(request_ids)+ assert CONSTANT_ID_FROM_HASHED_PLACEHOLDER not in request_ids+++ @pytest.mark.parametrize("call_type", ["aretrieve_batch", "acreate_file"])+ def test_get_spend_logs_id_keys_off_batch_identity_when_the_body_was_redacted(call_type):+ """Retrieving one batch twice must produce one row, not two. Redaction strips the id+ off the response body, so the identity has to come from the standard logging payload,+ which is built from the unredacted response and keeps it. Falling through to the+ per-call id here would write a second row carrying the same batch's full cost and+ overstate spend by a multiple of how often the caller polled."""+ standard_logging_object = {"id": "batch_abc123"}+ first = get_spend_logs_id(+ call_type,+ dict(REDACTED_RESPONSE_PLACEHOLDER),+ {"litellm_call_id": "call-id-1", "standard_logging_object": standard_logging_object},+ )+ second = get_spend_logs_id(+ call_type,+ dict(REDACTED_RESPONSE_PLACEHOLDER),+ {"litellm_call_id": "call-id-2", "standard_logging_object": standard_logging_object},+ )++ expected = "batch_abc123_batch_cost" if call_type == "aretrieve_batch" else "batch_abc123"+ assert first == second == expected+ assert first != CONSTANT_ID_FROM_HASHED_PLACEHOLDER+++ def test_get_spend_logs_id_separates_distinct_batches_whose_bodies_were_both_redacted():+ """The flip side of idempotency: two different batches must not share a row just+ because redaction flattened both bodies to the same placeholder."""+ ids = [+ get_spend_logs_id(+ "aretrieve_batch",+ dict(REDACTED_RESPONSE_PLACEHOLDER),+ {"litellm_call_id": f"call-id-{index}", "standard_logging_object": {"id": batch_id}},+ )+ for index, batch_id in enumerate(("batch_first", "batch_second"))+ ]++ assert ids == ["batch_first_batch_cost", "batch_second_batch_cost"]+++ def test_get_spend_logs_id_prefers_the_response_id_over_the_standard_logging_id():+ """An unredacted response keeps deciding its own row key, so cache-hit ids and every+ other call type behave exactly as they did before."""+ assert (+ get_spend_logs_id(+ "acompletion",+ {"id": "chatcmpl-from-response"},+ {"litellm_call_id": "call-id-1", "standard_logging_object": {"id": "id-from-standard-payload"}},+ )+ == "chatcmpl-from-response"+ )+++ def test_batch_cost_row_does_not_collide_with_the_batch_creation_row():+ """Creating a batch writes a row keyed by the batch's own id, so keying the cost row+ the same way makes the insert a duplicate of it. request_id is the primary key and the+ flush skips duplicates, so the cost row is dropped with no error and the batch is+ billed nothing. Observed against a live proxy: the poller computed and flushed the+ cost, and the only row carrying that id was the acreate_batch row written when the+ batch was submitted."""+ batch_id = "bGl0ZWxsbV9wcm94eTttb2RlbF9pZDphYmM7bGxtX2JhdGNoX2lkOnh5eg"++ creation_row_id = get_spend_logs_id("acreate_batch", {"id": batch_id}, {"litellm_call_id": "call-create"})+ cost_row_id = get_spend_logs_id(+ "aretrieve_batch",+ dict(REDACTED_RESPONSE_PLACEHOLDER),+ {"litellm_call_id": "call-poller", "standard_logging_object": {"id": batch_id}},+ )++ assert creation_row_id == batch_id+ assert cost_row_id != creation_row_id+ assert cost_row_id == f"{batch_id}_batch_cost"+++ def test_batch_cost_row_id_is_stable_across_repeated_accounting():+ """The cost row stays keyed to the batch, so accounting the same batch twice collapses+ to one row instead of billing it twice."""+ standard_logging_object = {"id": "batch_same"}+ ids = [+ get_spend_logs_id(+ "aretrieve_batch",+ dict(REDACTED_RESPONSE_PLACEHOLDER),+ {"litellm_call_id": f"call-{index}", "standard_logging_object": standard_logging_object},+ )+ for index in range(2)+ ]++ assert ids[0] == ids[1] == "batch_same_batch_cost"+++ def _make_failed_request_standard_logging_payload() -> StandardLoggingPayload:+ base: Final = _make_standard_logging_payload_with_usage_object(usage_object={})+ return cast(+ StandardLoggingPayload,+ {+ **base,+ "status": "failure",+ "call_type": "aresponses",+ "model_id": "mid-123",+ "model_group": "group-x",+ "api_base": "https://api.openai.com/v1/responses",+ "custom_llm_provider": "openai",+ },+ )+++ def test_get_logging_payload_failed_request_falls_back_to_standard_logging_payload():+ """Failed-request kwargs from the proxy failure hook carry no deployment info+ (LIT-5795), so the attribution columns must come from the failure-time+ standard_logging_object."""+ payload = get_logging_payload(+ kwargs={+ "model": "group-x",+ "litellm_params": {"metadata": {"user_api_key": "test-key", "status": "failure"}},+ "standard_logging_object": _make_failed_request_standard_logging_payload(),+ },+ response_obj={},+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ assert payload["model_id"] == "mid-123"+ assert payload["model_group"] == "group-x"+ assert payload["api_base"] == "https://api.openai.com/v1/responses"+ assert payload["custom_llm_provider"] == "openai"+++ def test_get_logging_payload_request_kwargs_win_over_standard_logging_payload():+ payload = get_logging_payload(+ kwargs={+ "model": "group-y",+ "custom_llm_provider": "anthropic",+ "litellm_params": {+ "api_base": "https://kwargs.example.com",+ "metadata": {+ "user_api_key": "test-key",+ "model_group": "kwargs-group",+ "model_info": {"id": "kwargs-mid"},+ },+ },+ "standard_logging_object": _make_failed_request_standard_logging_payload(),+ },+ response_obj={},+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ assert payload["model_id"] == "kwargs-mid"+ assert payload["model_group"] == "kwargs-group"+ assert payload["api_base"] == "https://kwargs.example.com"+ assert payload["custom_llm_provider"] == "anthropic"+++ def test_get_logging_payload_failed_request_without_standard_logging_payload_leaves_fields_empty():+ payload = get_logging_payload(+ kwargs={+ "model": "group-x",+ "litellm_params": {"metadata": {"user_api_key": "test-key", "status": "failure"}},+ },+ response_obj={},+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )+ assert payload["model_id"] == ""+ assert payload["model_group"] == ""+ assert payload["api_base"] == ""+ assert payload["custom_llm_provider"] == ""+++++@patch("litellm.proxy.proxy_server.master_key", None)+@patch("litellm.proxy.proxy_server.general_settings", {})+def test_get_logging_payload_empty_key_slp_none_is_empty_string_not_none_literal():+ kwargs = {+ "model": "openai/gpt-4.1",+ "messages": [{"role": "user", "content": "Hello"}],+ "call_type": "acompletion",+ "litellm_params": {+ "metadata": {+ "user_api_key_user_id": "test_user",+ }+ },+ }+ payload = get_logging_payload(+ kwargs=kwargs,+ response_obj=Exception("error"),+ start_time=datetime.datetime.now(timezone.utc),+ end_time=datetime.datetime.now(timezone.utc),+ )++ assert payload["api_key"] == "", (+ f"Expected empty string but got {payload['api_key']!r}; "+ "dropping _redact_logged_api_key's 'or \"\"' guard would yield 'None' here"+ )+++def test_get_spend_logs_metadata_sibling_fields_preserved():+ raw = "anthropic-raw-key-xyz"+ meta = _get_spend_logs_metadata(+ {+ "user_api_key": raw,+ "user_api_key_alias": "my-alias",+ "user_api_key_team_id": "team-123",+ }+ )+ assert meta["user_api_key"] == hash_token(raw)+ assert meta["user_api_key_alias"] == "my-alias"+ assert meta["user_api_key_team_id"] == "team-123"+++def test_redact_logged_api_key_partial_sha256_is_hashed():+ partial_hex = "a" * 63+ result = _redact_logged_api_key(partial_hex)+ assert result is not None+ assert result != partial_hex+ assert len(result) == 64+ assert result == hash_token(partial_hex)+++def test_redact_logged_api_key_bearer_already_hashed_passes_through_with_flag():+ already_hashed = hash_token("sk-some-key")+ assert len(already_hashed) == 64+ result = _redact_logged_api_key(f"Bearer {already_hashed}", already_hashed=True)+ assert result == already_hashed+ assert hash_token(already_hashed) != result+++def test_redact_logged_api_key_bearer_sha256_without_flag_is_hashed():+ already_hashed = hash_token("sk-some-key")+ assert len(already_hashed) == 64+ result = _redact_logged_api_key(f"Bearer {already_hashed}")+ assert result is not None+ assert result != already_hashed+ assert result == hash_token(already_hashed)