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(vertex): report an unreadable credentials file as a read failure (#40173)
Kolade Fajimi35970c3eacb9
diff --git a/litellm-rust/Cargo.lock b/litellm-rust/Cargo.lockindex dedd41b2efc..afec2550469 100644--- a/litellm-rust/Cargo.lock+++ b/litellm-rust/Cargo.lock@@ -3406,6 +3406,7 @@ dependencies = [name = "litellm-auth-gcp"version = "0.1.0"dependencies = [+ "base64 0.22.1","gcp_auth","google-cloud-auth","http 1.4.2",diff --git a/litellm-rust/crates/auth-gcp/Cargo.toml b/litellm-rust/crates/auth-gcp/Cargo.tomlindex 24791ce7b53..bb4c022580a 100644--- a/litellm-rust/crates/auth-gcp/Cargo.toml+++ b/litellm-rust/crates/auth-gcp/Cargo.toml@@ -11,6 +11,7 @@ google-sdk = ["dep:google-cloud-auth", "dep:http"][dependencies]litellm-auth-types.workspace = true+base64.workspace = truemoka.workspace = trueserde.workspace = trueserde_json.workspace = truediff --git a/litellm-rust/crates/auth-gcp/src/auth.rs b/litellm-rust/crates/auth-gcp/src/auth.rsindex d7c434fe26e..e09a350c012 100644--- a/litellm-rust/crates/auth-gcp/src/auth.rs+++ b/litellm-rust/crates/auth-gcp/src/auth.rs@@ -1,4 +1,4 @@-use std::{future::Future, path::Path, pin::Pin, sync::Arc};+use std::{future::Future, pin::Pin, sync::Arc};use gcp_auth::{CustomServiceAccount, TokenProvider};use litellm_auth_types::{CredentialPlacement, Error, ErrorDetail, http::apply_credential};@@ -8,7 +8,8 @@ use sha2::{Digest, Sha256};use crate::{config::{- CredentialSource, VertexConfig, credential_source, get_vertex_ai_project, non_empty_env,+ CredentialSource, VertexConfig, credential_source, get_vertex_ai_project,+ is_base64_encoded_json, names_a_credentials_file, non_empty_env,},constants::{CLOUD_PLATFORM_SCOPE, GOOGLE_OAUTH_TOKEN_ENDPOINT, VERTEX_AI_API_KEY_ENV,@@ -176,14 +177,7 @@ impl VertexProviderLoader for GcpProviderLoader {.map_err(auth_acquisition_error)?,),CredentialSource::Trusted(configured) => {- let configured = configured.expose();- let service_account = if Path::new(configured).is_file() {- CustomServiceAccount::from_file(configured)- } else {- CustomServiceAccount::from_json(configured)- }- .map_err(auth_acquisition_error)?;- Arc::new(service_account)+ Arc::new(load_trusted_service_account(configured.expose())?)}CredentialSource::ApplicationCredentials(path) => {Arc::new(CustomServiceAccount::from_file(path).map_err(auth_acquisition_error)?)@@ -240,6 +234,23 @@ enum CredentialCacheKey {Adc,}+const BASE64_CREDENTIALS: &str = "The `vertex_credentials` value is base64-encoded JSON, not the JSON itself. \+ Set it to a readable file path, or to the credentials JSON itself.";++fn load_trusted_service_account(configured: &str) -> Result<CustomServiceAccount, Error> {+ if is_base64_encoded_json(configured) {+ return Err(Error::InvalidConfiguration(ErrorDetail::Message(+ BASE64_CREDENTIALS.into(),+ )));+ }+ if names_a_credentials_file(configured) {+ CustomServiceAccount::from_file(configured)+ } else {+ CustomServiceAccount::from_json(configured)+ }+ .map_err(auth_acquisition_error)+}+fn auth_acquisition_error(error: gcp_auth::Error) -> Error {Error::CredentialAcquisition(litellm_auth_types::ErrorDetail::failed("Vertex AI credentials",@@ -264,6 +275,73 @@ mod tests {assert_eq!(validate_request_credentials(credentials).is_ok(), accepted);}+ #[rstest::rstest]+ #[case::missing_file(+ "/nonexistent/vertex-key.json",+ "failed to open application credentials file"+ )]+ #[case::malformed_json(+ " {\"type\": \"service_account\",",+ "failed to deserialize ApplicationCredentials"+ )]+ #[case::quoted_json(+ "'{\"type\": \"service_account\"}'",+ "failed to deserialize ApplicationCredentials"+ )]+ #[tokio::test]+ async fn trusted_credentials_are_read_as_a_file_unless_they_are_json(+ #[case] configured: &str,+ #[case] expected: &str,+ ) {+ let Err(error) = GcpProviderLoader+ .load(CredentialSource::Trusted(SecretValue::new(configured)))+ .await+ else {+ panic!("{configured:?} should not load");+ };+ assert!(error.to_string().contains(expected), "{error}");+ }++ #[rstest::rstest]+ #[case::padded("eyJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCJ9")]+ #[case::quoted_prefixed_unpadded("\"base64:eyJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCJ9\"")]+ #[case::url_safe_wrapped("eyJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsICJr\nZXkiOiAiPz8_In0=")]+ #[tokio::test]+ async fn base64_encoded_credentials_are_named_as_base64(#[case] configured: &str) {+ assert!(+ trusted_load_error(configured)+ .await+ .contains("is base64-encoded JSON, not the JSON itself")+ );+ }++ async fn trusted_load_error(configured: &str) -> String {+ match GcpProviderLoader+ .load(CredentialSource::Trusted(SecretValue::new(configured)))+ .await+ {+ Ok(_) => panic!("{configured:?} should not load"),+ Err(error) => error.to_string(),+ }+ }++ #[rstest::rstest]+ #[tokio::test]+ async fn a_relative_key_file_named_like_json_is_read_as_a_file() {+ let key = tempfile::Builder::new()+ .prefix("{vertex")+ .suffix(".json")+ .tempfile_in(".")+ .unwrap();+ std::fs::write(key.path(), r#"{"project_id":"file-project"}"#).unwrap();+ let relative_name = key.path().file_name().unwrap().to_str().unwrap();+ let absolute_path = std::fs::canonicalize(key.path()).unwrap();+ assert_eq!(+ trusted_load_error(relative_name).await,+ trusted_load_error(absolute_path.to_str().unwrap()).await+ );+ }+#[rstest::rstest]fn inline_and_trusted_credentials_never_share_a_cache_entry() {assert_ne!(diff --git a/litellm-rust/crates/auth-gcp/src/config.rs b/litellm-rust/crates/auth-gcp/src/config.rsindex 0a76bf93cf0..5444897aaaf 100644--- a/litellm-rust/crates/auth-gcp/src/config.rs+++ b/litellm-rust/crates/auth-gcp/src/config.rs@@ -1,5 +1,9 @@use std::{collections::BTreeMap, path::Path};+use base64::{+ Engine, alphabet,+ engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig},+};use litellm_auth_types::{Error, ErrorDetail, InputSource, SecretValue, Sourced};use serde_json::{Map, Value};@@ -80,9 +84,10 @@ pub fn get_vertex_ai_project_from_credentials(CredentialSource::Inline(configured) => configured.expose().to_string(),CredentialSource::Trusted(configured) => {let configured = configured.expose();- match std::fs::read_to_string(configured) {- Ok(contents) if Path::new(configured).is_file() => contents,- _ => configured.to_string(),+ if names_a_credentials_file(configured) {+ std::fs::read_to_string(configured).ok()?+ } else {+ configured.to_string()}}CredentialSource::ApplicationCredentials(path) => std::fs::read_to_string(path).ok()?,@@ -105,6 +110,32 @@ pub fn get_vertex_ai_location(.or_else(|| VertexParams::LOCATION.resolve(&|_| None, env_lookup))}+const INLINE_JSON_LEADING_NOISE: [char; 7] = [' ', '\t', '\r', '\n', '\u{feff}', '"', '\''];++fn is_inline_json(configured: &str) -> bool {+ configured+ .trim_start_matches(INLINE_JSON_LEADING_NOISE)+ .starts_with('{')+}++pub(crate) fn names_a_credentials_file(configured: &str) -> bool {+ !is_inline_json(configured) || Path::new(configured).is_file()+}++const BASE64_ANY_PADDING: GeneralPurpose = GeneralPurpose::new(+ &alphabet::STANDARD,+ GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),+);++pub(crate) fn is_base64_encoded_json(configured: &str) -> bool {+ let compact: String = configured.split_whitespace().collect();+ let quoted = compact.trim_matches(['"', '\'']);+ let encoded = quoted.strip_prefix("base64:").unwrap_or(quoted);+ BASE64_ANY_PADDING+ .decode(encoded.replace('-', "+").replace('_', "/"))+ .is_ok_and(|decoded| serde_json::from_slice::<Map<String, Value>>(&decoded).is_ok())+}+#[derive(Clone, Debug)]pub enum CredentialSource {Inline(SecretValue),diff --git a/litellm-rust/crates/auth-gcp/tests/vertex_config.rs b/litellm-rust/crates/auth-gcp/tests/vertex_config.rsindex 3a589ab5266..979386f0c01 100644--- a/litellm-rust/crates/auth-gcp/tests/vertex_config.rs+++ b/litellm-rust/crates/auth-gcp/tests/vertex_config.rs@@ -93,3 +93,22 @@ fn project_is_read_from_the_credentials_that_would_authenticate() {None);}++#[rstest]+fn project_is_read_from_a_relative_key_file_named_like_json() {+ let key = tempfile::Builder::new()+ .prefix("{vertex")+ .suffix(".json")+ .tempfile_in(".")+ .unwrap();+ std::fs::write(key.path(), r#"{"project_id":"file-project"}"#).unwrap();+ let relative_name = key.path().file_name().unwrap().to_str().unwrap();+ let from_file = VertexConfig::from_params(&VertexParams {+ vertex_credentials: Some(relative_name.into()),+ ..VertexParams::default()+ });+ assert_eq!(+ get_vertex_ai_project_from_credentials(&from_file, &|_| None).as_deref(),+ Some("file-project")+ );+}diff --git a/litellm/llms/vertex_ai/credentials_source.py b/litellm/llms/vertex_ai/credentials_source.pynew file mode 100644index 00000000000..ad51fd1e69d--- /dev/null+++ b/litellm/llms/vertex_ai/credentials_source.py@@ -0,0 +1,200 @@+import base64+import os+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Final, NoReturn, TypeAlias, TypeVar++from pydantic import TypeAdapter, ValidationError+from typing_extensions import assert_never++from litellm._logging import verbose_logger+from litellm.litellm_core_utils.secret_redaction import redact_string+++@dataclass(frozen=True, slots=True)+class VertexCredentialsJson:+ value: Mapping[str, object]+ path: str | None+++@dataclass(frozen=True, slots=True)+class VertexCredentialsFileUnreadable:+ path: str+ reason: str+++@dataclass(frozen=True, slots=True)+class VertexCredentialsFileInvalid:+ path: str+ problem: str+++@dataclass(frozen=True, slots=True)+class VertexCredentialsInlineNotJson:+ detail: str+ hint: str+++@dataclass(frozen=True, slots=True)+class VertexCredentialsUnusable:+ problem: str+++@dataclass(frozen=True, slots=True)+class _InvalidJson:+ detail: str+++@dataclass(frozen=True, slots=True)+class _JsonNotAnObject:+ pass+++VertexCredentialsFailure: TypeAlias = (+ VertexCredentialsFileUnreadable+ | VertexCredentialsFileInvalid+ | VertexCredentialsInlineNotJson+ | VertexCredentialsUnusable+)+VertexCredentialsSource: TypeAlias = VertexCredentialsJson | VertexCredentialsFailure+_VertexCredentialsFile: TypeAlias = (+ VertexCredentialsJson | VertexCredentialsFileUnreadable | VertexCredentialsFileInvalid+)+_ParsedJson: TypeAlias = Mapping[str, object] | _InvalidJson | _JsonNotAnObject+_Credentials = TypeVar("_Credentials")+++_JSON_OBJECT_ADAPTER: Final = TypeAdapter(dict[str, object])+_INLINE_JSON_LEADING_NOISE: Final = " \t\r\n\"'"+_BASE64_PREFIX: Final = "base64:"+_MAX_LOGGED_PATH_LENGTH: Final = 260+_MAX_CREDENTIALS_FILE_CHARACTERS: Final = 1 << 20+_NOT_A_JSON_OBJECT: Final = "is JSON but not a JSON object, it may be quoted or encoded twice"+_PRIVATE_KEY_HINT: Final = "Check for unescaped newlines in private_key."+_LEADING_NOISE_HINT: Final = "Remove the quotes or byte-order mark before the opening `{`."+_FILE_FAILURE_MESSAGE: Final = (+ "Unable to load the vertex credentials file. LiteLLM's log names the path and the reason."+)+++def _parse_json_object(raw: str | bytes) -> _ParsedJson:+ try:+ return _JSON_OBJECT_ADAPTER.validate_json(raw)+ except ValidationError as e:+ errors: Final = e.errors()+ if any(error["type"] == "json_invalid" for error in errors):+ return _InvalidJson("; ".join(error["msg"] for error in errors))+ return _JsonNotAnObject()+++def _read_json_file(path: str) -> _VertexCredentialsFile:+ try:+ with open(path, encoding="utf-8") as f:+ contents: Final = f.read(_MAX_CREDENTIALS_FILE_CHARACTERS + 1)+ except OSError as e:+ return VertexCredentialsFileUnreadable(path, f"{e.strerror or 'OS error'} ({type(e).__name__})")+ except UnicodeDecodeError:+ return VertexCredentialsFileInvalid(path, "is not UTF-8 text")+ except ValueError as e:+ return VertexCredentialsFileUnreadable(path, f"{e} ({type(e).__name__})")++ if len(contents) > _MAX_CREDENTIALS_FILE_CHARACTERS:+ return VertexCredentialsFileInvalid(+ path, f"is over {_MAX_CREDENTIALS_FILE_CHARACTERS} characters, larger than any credentials file"+ )+ parsed: Final = _parse_json_object(contents)+ match parsed:+ case _InvalidJson(detail=detail):+ return VertexCredentialsFileInvalid(path, f"is not valid JSON: {detail}. {_PRIVATE_KEY_HINT}")+ case _JsonNotAnObject():+ return VertexCredentialsFileInvalid(path, _NOT_A_JSON_OBJECT)+ case _:+ return VertexCredentialsJson(parsed, path)+++def _is_inline_credentials_json(credentials: str) -> bool:+ return credentials.lstrip(_INLINE_JSON_LEADING_NOISE).startswith("{")+++def _is_base64_encoded_json(credentials: str) -> bool:+ encoded: Final = "".join(credentials.split()).strip("\"'").removeprefix(_BASE64_PREFIX)+ standard_alphabet: Final = encoded.replace("-", "+").replace("_", "/")+ try:+ decoded: Final = base64.b64decode(standard_alphabet + "=" * (-len(encoded) % 4), validate=True)+ except ValueError:+ return False+ return isinstance(_parse_json_object(decoded), Mapping)+++def _load_inline_credentials(credentials: str) -> VertexCredentialsSource:+ inline: Final = _parse_json_object(credentials)+ if isinstance(inline, Mapping):+ return VertexCredentialsJson(inline, None)+ if os.path.isfile(credentials):+ return _read_json_file(credentials)++ match inline:+ case _JsonNotAnObject():+ return VertexCredentialsUnusable(_NOT_A_JSON_OBJECT)+ case _InvalidJson(detail=detail) if credentials.lstrip().startswith("{"):+ return VertexCredentialsInlineNotJson(detail, _PRIVATE_KEY_HINT)+ case _InvalidJson(detail=detail):+ return VertexCredentialsInlineNotJson(detail, _LEADING_NOISE_HINT)+ case _: # pragma: no cover - exhaustiveness guard, unreachable while the union holds+ assert_never(inline) # pragma: no cover+++def load_vertex_credentials_source(credentials: str) -> VertexCredentialsSource:+ if not credentials.strip():+ return VertexCredentialsUnusable("is empty")++ inline_first: Final = _is_inline_credentials_json(credentials)+ verbose_logger.debug(+ "Vertex: Loading vertex credentials, is_file_path=%s, current dir %s", not inline_first, os.getcwd()+ )+ if inline_first:+ return _load_inline_credentials(credentials)+ if _is_base64_encoded_json(credentials):+ return VertexCredentialsUnusable("is base64-encoded JSON, not the JSON itself")+ return _read_json_file(credentials)+++def build_vertex_credentials(+ source: VertexCredentialsJson, build: Callable[[Mapping[str, object]], _Credentials]+) -> _Credentials:+ if source.path is None:+ return build(source.value)+ try:+ return build(source.value)+ except ValueError as e:+ rejected: Final = VertexCredentialsFileInvalid(source.path, f"holds credentials that cannot be used: {e}")+ raise_vertex_credentials_failure(rejected)+++def _path_for_log(path: str) -> str:+ if len(path) > _MAX_LOGGED_PATH_LENGTH:+ return f"<a {len(path)}-character value>"+ return repr(redact_string(path))+++def raise_vertex_credentials_failure(failure: VertexCredentialsFailure) -> NoReturn:+ match failure:+ case VertexCredentialsFileUnreadable():+ verbose_logger.error(+ "Vertex: cannot read the credentials file at %s: %s", _path_for_log(failure.path), failure.reason+ )+ raise ValueError(_FILE_FAILURE_MESSAGE)+ case VertexCredentialsFileInvalid():+ verbose_logger.error("Vertex: the credentials file at %s %s", _path_for_log(failure.path), failure.problem)+ raise ValueError(_FILE_FAILURE_MESSAGE)+ case VertexCredentialsInlineNotJson():+ raise ValueError(+ f"The inline `vertex_credentials` value is not valid JSON: {failure.detail}. {failure.hint}"+ )+ case VertexCredentialsUnusable():+ raise ValueError(+ f"The `vertex_credentials` value {failure.problem}. "+ "Set it to a readable file path, or to the credentials JSON itself."+ )+ case _: # pragma: no cover - exhaustiveness guard, unreachable while the union holds+ assert_never(failure) # pragma: no coverdiff --git a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py b/litellm/llms/vertex_ai/vertex_ai_aws_wif.pyindex 577e9d2845c..34dd9ab03e8 100644--- a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py+++ b/litellm/llms/vertex_ai/vertex_ai_aws_wif.py@@ -9,6 +9,7 @@ uses BaseAWSLLM to obtain AWS credentials and wraps them in a customAwsSecurityCredentialsSupplier for google-auth."""+from collections.abc import Mappingfrom typing import FinalGOOGLE_IMPORT_ERROR_MESSAGE: Final = (@@ -40,14 +41,14 @@ class VertexAIAwsWifAuth:"""@staticmethod- def extract_aws_params(json_obj: dict) -> dict[str, str]:+ def extract_aws_params(json_obj: Mapping[str, object]) -> Mapping[str, object]:"""Extract LiteLLM-specific aws_* keys from a WIF credential JSON dict.Returns a dict of {param_name: value} for any recognized aws_* keysfound in the JSON. Returns empty dict if none are present."""- return {key: json_obj[key] for key in _AWS_CREDENTIAL_KEYS if key in json_obj}+ return {key: value for key, value in json_obj.items() if key in _AWS_CREDENTIAL_KEYS}@staticmethoddef credentials_from_explicit_aws(json_obj, aws_params, scopes):diff --git a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py b/litellm/llms/vertex_ai/vertex_ai_non_gemini.pyindex a7a1ea8d88d..9d960845fd3 100644--- a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py+++ b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py@@ -1,4 +1,3 @@-import jsonimport osimport timefrom collections.abc import Callable@@ -10,6 +9,12 @@ import litellmfrom litellm.litellm_core_utils.core_helpers import map_finish_reasonfrom litellm.llms.bedrock.common_utils import ModelResponseIteratorfrom litellm.llms.custom_httpx.http_handler import _DEFAULT_TTL_FOR_HTTPX_CLIENTS+from litellm.llms.vertex_ai.credentials_source import (+ VertexCredentialsJson,+ build_vertex_credentials,+ load_vertex_credentials_source,+ raise_vertex_credentials_failure,+)from litellm.types.llms.vertex_ai import *from litellm.utils import CustomStreamWrapper, ModelResponse, Usage@@ -132,11 +137,15 @@ def completion(if vertex_credentials is not None and isinstance(vertex_credentials, str):import google.oauth2.service_account- json_obj: Final = json.loads(vertex_credentials)+ source: Final = load_vertex_credentials_source(vertex_credentials)+ if not isinstance(source, VertexCredentialsJson):+ raise_vertex_credentials_failure(source)- creds = google.oauth2.service_account.Credentials.from_service_account_info(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],+ creds = build_vertex_credentials(+ source,+ lambda info: google.oauth2.service_account.Credentials.from_service_account_info(+ info, scopes=["https://www.googleapis.com/auth/cloud-platform"]+ ),)else:creds, _ = google.auth.default(quota_project_id=vertex_project)diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.pyindex 1d5cbe09ba0..77508096e4a 100644--- a/litellm/llms/vertex_ai/vertex_llm_base.py+++ b/litellm/llms/vertex_ai/vertex_llm_base.py@@ -6,7 +6,6 @@ Handles Authentication and generating request urls for Vertex AI and Google AI Simport asyncioimport json-import osimport threadingfrom collections.abc import Mappingfrom typing import TYPE_CHECKING, Any, Final, Literal, Protocol@@ -26,6 +25,12 @@ from .common_utils import (get_vertex_base_url,get_vertex_url,)+from .credentials_source import (+ VertexCredentialsJson,+ build_vertex_credentials,+ load_vertex_credentials_source,+ raise_vertex_credentials_failure,+)def graft_default_vertex_path(api_base: str, default_url: str) -> str:@@ -129,83 +134,21 @@ class VertexBase:) -> tuple[_VertexCredentialsObject | None, str]:if credentials is not None:if isinstance(credentials, str):- _is_path: Final = os.path.exists(- credentials- ) # credentials is from server config (litellm_params), not user input- verbose_logger.debug(- "Vertex: Loading vertex credentials, is_file_path=%s, current dir %s",- _is_path,- os.getcwd(),- )-- try:- if _is_path:- with open(credentials) as f:- json_obj = json.load(f)- else:- json_obj = json.loads(credentials)- except Exception as e:- raise Exception(- "Unable to load vertex credentials from environment. "- "Ensure the JSON is valid (check for unescaped newlines in private_key). "- f"Parse error: {type(e).__name__}"- )+ source: Final = load_vertex_credentials_source(credentials)+ if not isinstance(source, VertexCredentialsJson):+ raise_vertex_credentials_failure(source)+ json_obj: Mapping[str, object] = source.value+ creds = build_vertex_credentials(source, self._credentials_from_json)elif isinstance(credentials, dict):json_obj = credentials+ creds = self._credentials_from_json(credentials)else:raise ValueError(f"Invalid credentials type: {type(credentials)}")- # Check if the JSON object contains Workload Identity Federation configuration- if "type" in json_obj and json_obj["type"] == "external_account":- # If environment_id key contains "aws" value it corresponds to an AWS config file- credential_source: Final = json_obj.get("credential_source", {})- environment_id: Final = (- credential_source.get("environment_id", "") if isinstance(credential_source, dict) else ""- )- if isinstance(environment_id, str) and "aws" in environment_id:- # Check if explicit AWS params are in the JSON (bypasses metadata)- from litellm.llms.vertex_ai.vertex_ai_aws_wif import (- VertexAIAwsWifAuth,- )-- aws_params: Final = VertexAIAwsWifAuth.extract_aws_params(json_obj)- if aws_params:- creds = VertexAIAwsWifAuth.credentials_from_explicit_aws(- json_obj,- aws_params=aws_params,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- else:- creds = self._credentials_from_identity_pool_with_aws(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- elif isinstance(credential_source, dict) and "executable" in credential_source:- creds = self._credentials_from_pluggable(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- else:- creds = self._credentials_from_identity_pool(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- # Check if the JSON object contains Authorized User configuration (via gcloud auth application-default login)- elif "type" in json_obj and json_obj["type"] == "authorized_user":- creds = self._credentials_from_authorized_user(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )- if project_id is None:- project_id = (- creds.quota_project_id- ) # authorized user credentials don't have a project_id, only quota_project_id- else:- creds = self._credentials_from_service_account(- json_obj,- scopes=["https://www.googleapis.com/auth/cloud-platform"],- )-+ if project_id is None and json_obj.get("type") == "authorized_user":+ project_id = (+ creds.quota_project_id+ ) # authorized user credentials don't have a project_id, only quota_project_idif project_id is None:project_id = getattr(creds, "project_id", None)else:@@ -225,6 +168,54 @@ class VertexBase:return creds, project_id+ def _credentials_from_json(self, json_obj: Mapping[str, object]) -> _VertexCredentialsObject:+ # Check if the JSON object contains Workload Identity Federation configuration+ if "type" in json_obj and json_obj["type"] == "external_account":+ # If environment_id key contains "aws" value it corresponds to an AWS config file+ credential_source: Final = json_obj.get("credential_source", {})+ environment_id: Final = (+ credential_source.get("environment_id", "") if isinstance(credential_source, dict) else ""+ )+ if isinstance(environment_id, str) and "aws" in environment_id:+ # Check if explicit AWS params are in the JSON (bypasses metadata)+ from litellm.llms.vertex_ai.vertex_ai_aws_wif import (+ VertexAIAwsWifAuth,+ )++ aws_params: Final = VertexAIAwsWifAuth.extract_aws_params(json_obj)+ if aws_params:+ return VertexAIAwsWifAuth.credentials_from_explicit_aws(+ json_obj,+ aws_params=aws_params,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ else:+ return self._credentials_from_identity_pool_with_aws(+ json_obj,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ elif isinstance(credential_source, dict) and "executable" in credential_source:+ return self._credentials_from_pluggable(+ json_obj,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ else:+ return self._credentials_from_identity_pool(+ json_obj,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ # Check if the JSON object contains Authorized User configuration (via gcloud auth application-default login)+ elif "type" in json_obj and json_obj["type"] == "authorized_user":+ return self._credentials_from_authorized_user(+ json_obj,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+ else:+ return self._credentials_from_service_account(+ json_obj,+ scopes=["https://www.googleapis.com/auth/cloud-platform"],+ )+# Google Auth Helpers -- extracted for mocking purposes in testsdef _credentials_from_identity_pool(self, json_obj, scopes) -> _VertexCredentialsObject:try:diff --git a/tests/integration/providers/test_vertex_credentials_source_wire.py b/tests/integration/providers/test_vertex_credentials_source_wire.pynew file mode 100644index 00000000000..c66bb10f9a9--- /dev/null+++ b/tests/integration/providers/test_vertex_credentials_source_wire.py@@ -0,0 +1,464 @@+from __future__ import annotations++import base64+import itertools+import json+import uuid+from collections.abc import Callable, Generator+from concurrent.futures import ThreadPoolExecutor+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from typing import Final, Literal++import httpx+import pytest+from integration._support.client import Gateway, Scenario, list_value, object_value, string_value+from integration._support.process import graceful_stop_seconds, owned_proxy+from integration._support.vertex import service_account_json+from integration._support.wire import Reply, Request, Wire, wire_server+from pydantic import JsonValue, TypeAdapter+from typing_extensions import assert_never++CHAT_BACKEND: Final = "gemini-3.7-flash"+EMBED_BACKEND: Final = "gemini-embedding-2-preview"+PROJECT: Final = "scripted-project"+LOCATION: Final = "us-central1"+MODELS_PATH: Final = f"/v1/projects/{PROJECT}/locations/{LOCATION}/publishers/google/models"+CLAUDE_BACKEND: Final = "claude-opus-5-5"+CLAUDE_LOCATION: Final = "us-east5"+CLAUDE_TARGET: Final = (+ f"/v1/projects/{PROJECT}/locations/{CLAUDE_LOCATION}/publishers/anthropic/models/{CLAUDE_BACKEND}:rawPredict"+)+VALUES: Final = [0.5, 0.25]+FILE_MESSAGE: Final = "Unable to load the vertex credentials file. LiteLLM's log names the path and the reason."+VALUE_ADVICE: Final = "Set it to a readable file path, or to the credentials JSON itself."+PROXY_ROOT: Final = Path(__file__).resolve().parents[3]+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+Endpoint = Literal["chat", "chat_stream", "embeddings", "messages", "responses"]+ENDPOINTS: Final[tuple[Endpoint, ...]] = ("chat", "chat_stream", "embeddings", "messages", "responses")+BURST_ENDPOINTS: Final[tuple[Endpoint, ...]] = ("chat", "chat_stream", "embeddings")+++def prompt_text(body: dict[str, JsonValue]) -> str:+ content: Final = body["content"] if "content" in body else list_value(body["contents"])[-1]+ return string_value(object_value(list_value(object_value(content)["parts"])[0])["text"])+++def gemini_reply(text: str) -> dict[str, JsonValue]:+ return {+ "candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": "STOP"}],+ "usageMetadata": {"promptTokenCount": 3, "candidatesTokenCount": 2, "totalTokenCount": 5},+ "modelVersion": CHAT_BACKEND,+ }+++def vertex_peer(request: Request) -> Reply:+ assert request.method == "POST", request.method+ assert request.headers["authorization"] == "Bearer scripted-token", request.headers+ echo: Final = f"echo {prompt_text(JSON_OBJECT.validate_json(request.body))}"+ if request.target == f"{MODELS_PATH}/{EMBED_BACKEND}:embedContent":+ return Reply(body=json.dumps({"embedding": {"values": VALUES}}).encode())+ if request.target == f"{MODELS_PATH}/{CHAT_BACKEND}:streamGenerateContent?alt=sse":+ return Reply(content_type="text/event-stream", chunks=(f"data: {json.dumps(gemini_reply(echo))}\n\n".encode(),))+ assert request.target == f"{MODELS_PATH}/{CHAT_BACKEND}:generateContent", request.target+ return Reply(body=json.dumps(gemini_reply(echo)).encode())+++@dataclass(frozen=True, slots=True)+class Deployments:+ chat: str+ embeddings: str+++def register(scenario: Scenario, wire: Wire, credentials: JsonValue) -> Deployments:+ return Deployments(+ chat=deployment(scenario, wire, credentials, CHAT_BACKEND),+ embeddings=deployment(scenario, wire, credentials, EMBED_BACKEND),+ )+++def deployment(scenario: Scenario, wire: Wire, credentials: JsonValue, backend: str) -> str:+ return scenario.model(+ model=f"vertex_ai/{backend}",+ api_key=None,+ api_base=wire.url,+ vertex_project=PROJECT,+ vertex_location=LOCATION,+ vertex_credentials=credentials,+ )+++def body_of(response: httpx.Response) -> dict[str, JsonValue]:+ return JSON_OBJECT.validate_json(response.content)+++def stream_text(response: httpx.Response) -> str:+ lines: Final = tuple(line for line in response.text.splitlines() if line.startswith("data: "))+ assert lines[-1] == "data: [DONE]", response.text+ chunks: Final = tuple(JSON_OBJECT.validate_json(line.removeprefix("data: ")) for line in lines[:-1])+ deltas: Final = (+ object_value(object_value(list_value(chunk["choices"])[0])["delta"]) for chunk in chunks if chunk["choices"]+ )+ return "".join(string_value(delta["content"]) for delta in deltas if delta.get("content"))+++def responses_text(body: dict[str, JsonValue]) -> str:+ messages: Final = tuple(object_value(item) for item in list_value(body["output"]))+ contents: Final = tuple(list_value(message["content"]) for message in messages if message["type"] == "message")+ parts: Final = tuple(object_value(part) for part in itertools.chain.from_iterable(contents))+ return "".join(string_value(part["text"]) for part in parts if part["type"] == "output_text")+++def call(gateway: Gateway, endpoint: Endpoint, deployments: Deployments, text: str) -> httpx.Response:+ match endpoint:+ case "chat":+ return gateway.request(+ "POST",+ "/v1/chat/completions",+ {"model": deployments.chat, "messages": [{"role": "user", "content": text}]},+ )+ case "chat_stream":+ return gateway.request(+ "POST",+ "/v1/chat/completions",+ {"model": deployments.chat, "messages": [{"role": "user", "content": text}], "stream": True},+ )+ case "embeddings":+ return gateway.request("POST", "/v1/embeddings", {"model": deployments.embeddings, "input": [text]})+ case "messages":+ return gateway.request(+ "POST",+ "/v1/messages",+ {"model": deployments.chat, "max_tokens": 64, "messages": [{"role": "user", "content": text}]},+ )+ case "responses":+ return gateway.request("POST", "/v1/responses", {"model": deployments.chat, "input": text})+ case _:+ assert_never(endpoint)+++def answered(endpoint: Endpoint, response: httpx.Response, text: str) -> None:+ assert response.status_code == 200, response.text+ match endpoint:+ case "chat":+ assert (+ object_value(object_value(list_value(body_of(response)["choices"])[0])["message"])["content"]+ == f"echo {text}"+ )+ case "chat_stream":+ assert stream_text(response) == f"echo {text}"+ case "embeddings":+ assert object_value(list_value(body_of(response)["data"])[0])["embedding"] == VALUES+ case "messages":+ assert object_value(list_value(body_of(response)["content"])[0])["text"] == f"echo {text}"+ case "responses":+ assert responses_text(body_of(response)) == f"echo {text}"+ case _:+ assert_never(endpoint)+++def provider_saw(wire: Wire, text: str) -> None:+ received: Final = wire.drain()+ assert [prompt_text(JSON_OBJECT.validate_json(item.body)) for item in received] == [text], received+++@contextmanager+def proxy_cwd_file(contents: str) -> Generator[str]:+ name: Final = f"{{vertex-{uuid.uuid4().hex}}}.json"+ path: Final = PROXY_ROOT / name+ path.write_text(contents)+ try:+ yield name+ finally:+ path.unlink()+++def written(directory: Path, name: str, contents: str | bytes) -> str:+ path: Final = directory / name+ if isinstance(contents, bytes):+ path.write_bytes(contents)+ else:+ path.write_text(contents)+ return str(path)++[email protected]("endpoint", ENDPOINTS)[email protected]("form", ("inline", "file", "brace_named_file"))+def test_loadable_credentials_reach_vertex_on_every_endpoint(+ gateway: Gateway, tmp_path: Path, form: str, endpoint: Endpoint+) -> None:+ key: Final = service_account_json(PROJECT, gateway.upstream_url.rstrip("/"))+ text: Final = f"loadable {form} {endpoint} {uuid.uuid4().hex}"+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario, proxy_cwd_file(key) as brace_name:+ credentials: Final = {+ "inline": key,+ "file": written(tmp_path, "key.json", key),+ "brace_named_file": brace_name,+ }[form]+ deployments: Final = register(scenario, wire, credentials)+ answered(endpoint, call(gateway, endpoint, deployments, text), text)+ provider_saw(wire, text)+++@dataclass(frozen=True, slots=True)+class Unloadable:+ name: str+ value: Callable[[Path, str], JsonValue]+ message: str+++def _missing(directory: Path, _: str) -> JsonValue:+ return str(directory / "missing.json")+++def _directory(directory: Path, _: str) -> JsonValue:+ return str(directory)+++def _invalid_json_file(directory: Path, _: str) -> JsonValue:+ return written(directory, "truncated.json", '{"type": "service_account",')+++def _array_file(directory: Path, _: str) -> JsonValue:+ return written(directory, "array.json", "[]")+++def _latin1_file(directory: Path, _: str) -> JsonValue:+ return written(directory, "latin1.json", b'{"type": "\xe9"}')+++def _oversized_file(directory: Path, _: str) -> JsonValue:+ return written(directory, "huge.json", json.dumps({"type": "service_account", "pad": "a" * (1 << 20)}))+++def _incomplete_key_file(directory: Path, _: str) -> JsonValue:+ return written(directory, "incomplete.json", json.dumps({"type": "service_account", "project_id": PROJECT}))+++def _quoted_path(directory: Path, token_url: str) -> JsonValue:+ return f'"{written(directory, "key.json", service_account_json(PROJECT, token_url))}"'+++def _long_value(_: Path, __: str) -> JsonValue:+ return "x" * 5000+++def _truncated_inline(_: Path, __: str) -> JsonValue:+ return '{"type": "service_account", "private_key": "-----BEGIN'+++def _base64_inline(_: Path, token_url: str) -> JsonValue:+ return base64.b64encode(service_account_json(PROJECT, token_url).encode()).decode()+++def _bom_inline(_: Path, token_url: str) -> JsonValue:+ return "" + service_account_json(PROJECT, token_url)+++def _blank(_: Path, __: str) -> JsonValue:+ return " "+++UNLOADABLE: Final = (+ Unloadable("missing_file", _missing, FILE_MESSAGE),+ Unloadable("directory", _directory, FILE_MESSAGE),+ Unloadable("invalid_json_file", _invalid_json_file, FILE_MESSAGE),+ Unloadable("array_file", _array_file, FILE_MESSAGE),+ Unloadable("latin1_file", _latin1_file, FILE_MESSAGE),+ Unloadable("oversized_file", _oversized_file, FILE_MESSAGE),+ Unloadable("incomplete_key_file", _incomplete_key_file, FILE_MESSAGE),+ Unloadable("quoted_path", _quoted_path, FILE_MESSAGE),+ Unloadable("long_value", _long_value, FILE_MESSAGE),+ Unloadable(+ "truncated_inline",+ _truncated_inline,+ "The inline `vertex_credentials` value is not valid JSON: ",+ ),+ Unloadable("base64_inline", _base64_inline, f"value is base64-encoded JSON, not the JSON itself. {VALUE_ADVICE}"),+ Unloadable("bom_inline", _bom_inline, "Remove the quotes or byte-order mark before the opening `{`."),+ Unloadable("blank", _blank, f"The `vertex_credentials` value is empty. {VALUE_ADVICE}"),+)+++def refused(gateway: Gateway, wire: Wire, response: httpx.Response, message: str, hidden: str) -> None:+ assert response.status_code == 500, response.text+ assert message in response.text, response.text+ assert hidden not in response.text, response.text+ assert wire.drain() == (), "a request with unloadable credentials reached the provider"+ assert gateway.client.get("/health/liveliness").status_code == 200++[email protected]("endpoint", ENDPOINTS)[email protected]("case", UNLOADABLE, ids=tuple(case.name for case in UNLOADABLE))+def test_unloadable_credentials_answer_the_loader_message_without_the_path(+ gateway: Gateway, tmp_path: Path, case: Unloadable, endpoint: Endpoint+) -> None:+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario:+ deployments: Final = register(scenario, wire, case.value(tmp_path, gateway.upstream_url.rstrip("/")))+ response: Final = call(gateway, endpoint, deployments, f"unloadable {case.name} {uuid.uuid4().hex}")+ refused(gateway, wire, response, case.message, str(tmp_path))++[email protected]("endpoint", ENDPOINTS)+def test_unreadable_brace_named_file_answers_the_file_message(gateway: Gateway, endpoint: Endpoint) -> None:+ key: Final = service_account_json(PROJECT, gateway.upstream_url.rstrip("/"))+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario, proxy_cwd_file(key) as name:+ (PROXY_ROOT / name).chmod(0)+ deployments: Final = register(scenario, wire, name)+ response: Final = call(gateway, endpoint, deployments, f"unreadable {uuid.uuid4().hex}")+ refused(gateway, wire, response, FILE_MESSAGE, name)+++def test_a_key_file_created_after_a_failure_is_used_on_the_next_request(gateway: Gateway, tmp_path: Path) -> None:+ path: Final = tmp_path / "late.json"+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario:+ deployments: Final = register(scenario, wire, str(path))+ refused(gateway, wire, call(gateway, "chat", deployments, "before the file"), FILE_MESSAGE, str(path))+ path.write_text(service_account_json(PROJECT, gateway.upstream_url.rstrip("/")))+ answered("chat", call(gateway, "chat", deployments, "after the file"), "after the file")+ provider_saw(wire, "after the file")+++def test_repeated_failures_answer_identically_and_leave_other_deployments_working(+ gateway: Gateway, tmp_path: Path+) -> None:+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario:+ broken: Final = register(scenario, wire, str(tmp_path / "missing.json"))+ working: Final = register(scenario, wire, service_account_json(PROJECT, gateway.upstream_url.rstrip("/")))+ first: Final = call(gateway, "chat", broken, "same request")+ second: Final = call(gateway, "chat", broken, "same request")+ refused(gateway, wire, first, FILE_MESSAGE, str(tmp_path))+ refused(gateway, wire, second, FILE_MESSAGE, str(tmp_path))+ assert body_of(first)["error"] == body_of(second)["error"]+ answered("chat", call(gateway, "chat", working, "still working"), "still working")+ provider_saw(wire, "still working")++[email protected]("value", (5, ["a"]), ids=("int", "list"))+def test_non_string_credentials_are_refused_at_registration_without_a_provider_call(+ gateway: Gateway, value: JsonValue+) -> None:+ with wire_server(vertex_peer) as wire:+ response: Final = gateway.request(+ "POST",+ "/model/new",+ {+ "model_name": f"integration-{uuid.uuid4().hex}",+ "litellm_params": {+ "model": f"vertex_ai/{CHAT_BACKEND}",+ "api_base": wire.url,+ "vertex_project": PROJECT,+ "vertex_location": LOCATION,+ "vertex_credentials": value,+ },+ },+ )+ assert response.status_code == 422, response.text+ assert "vertex_credentials" in response.text, response.text+ assert wire.drain() == ()+ assert gateway.client.get("/health/liveliness").status_code == 200+++@dataclass(frozen=True, slots=True)+class Shot:+ healthy: bool+ endpoint: Endpoint+ text: str+++def test_concurrent_mixed_traffic_keeps_each_answer_on_its_own_deployment(gateway: Gateway, tmp_path: Path) -> None:+ key_path: Final = written(tmp_path, "key.json", service_account_json(PROJECT, gateway.upstream_url.rstrip("/")))+ with wire_server(vertex_peer) as wire, gateway.scenario() as scenario:+ good: Final = register(scenario, wire, key_path)+ bad: Final = register(scenario, wire, str(tmp_path / "missing.json"))+ plan: Final = tuple(+ Shot(index % 2 == 0, BURST_ENDPOINTS[index % 3], f"burst {index} {uuid.uuid4().hex}") for index in range(24)+ )++ def fire(shot: Shot) -> httpx.Response:+ return call(gateway, shot.endpoint, good if shot.healthy else bad, shot.text)++ with ThreadPoolExecutor(max_workers=12) as pool:+ responses: Final = tuple(pool.map(fire, plan))+ for shot, response in zip(plan, responses, strict=True):+ if shot.healthy:+ answered(shot.endpoint, response, shot.text)+ else:+ assert response.status_code == 500 and FILE_MESSAGE in response.text, response.text+ received: Final = sorted(prompt_text(JSON_OBJECT.validate_json(item.body)) for item in wire.drain())+ assert received == sorted(shot.text for shot in plan if shot.healthy)+ assert gateway.client.get("/health/liveliness").status_code == 200+++def claude_prompt(body: dict[str, JsonValue]) -> str:+ content: Final = object_value(list_value(body["messages"])[-1])["content"]+ if isinstance(content, str):+ return content+ return string_value(object_value(list_value(content)[0])["text"])+++def vertex_claude_peer(request: Request) -> Reply:+ assert request.method == "POST", request.method+ assert request.headers["authorization"] == "Bearer scripted-token", request.headers+ assert request.target == CLAUDE_TARGET, request.target+ reply: Final[dict[str, JsonValue]] = {+ "id": f"msg_{uuid.uuid4().hex}",+ "type": "message",+ "role": "assistant",+ "model": CLAUDE_BACKEND,+ "content": [{"type": "text", "text": f"echo {claude_prompt(JSON_OBJECT.validate_json(request.body))}"}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 3, "output_tokens": 2},+ }+ return Reply(body=json.dumps(reply).encode())++[email protected](2 * graceful_stop_seconds() + 120)+def test_rust_messages_route_loads_a_claude_key_file_and_names_unloadable_credentials(+ gateway: Gateway, tmp_path: Path+) -> None:+ token_url: Final = gateway.upstream_url.rstrip("/")+ key_path: Final = written(tmp_path, "key.json", service_account_json(PROJECT, token_url))+ encoded: Final = string_value(_base64_inline(tmp_path, token_url))+ (tmp_path / "rust").mkdir()+ with (+ wire_server(vertex_claude_peer) as wire,+ owned_proxy(gateway, tmp_path / "rust", {"LITELLM_RUST": "true"}, workers=2) as candidate,+ candidate.scenario() as scenario,+ ):++ def ask(credentials: str, text: str) -> httpx.Response:+ model: Final = scenario.model(+ model=f"vertex_ai/{CLAUDE_BACKEND}",+ api_key=None,+ api_base=wire.url,+ vertex_project=PROJECT,+ vertex_location=CLAUDE_LOCATION,+ vertex_credentials=credentials,+ )+ return candidate.request(+ "POST",+ "/v1/messages",+ {"model": model, "max_tokens": 64, "messages": [{"role": "user", "content": text}]},+ )++ loaded: Final = ask(key_path, "rust loads the file")+ assert loaded.status_code == 200, loaded.text+ assert object_value(list_value(body_of(loaded)["content"])[0])["text"] == "echo rust loads the file"+ assert [claude_prompt(JSON_OBJECT.validate_json(item.body)) for item in wire.drain()] == ["rust loads the file"]+ refused(+ candidate,+ wire,+ ask(str(tmp_path / "missing.json"), "rust refuses a missing file"),+ "failed to open application credentials file",+ str(tmp_path),+ )+ refused(+ candidate,+ wire,+ ask(encoded, "rust refuses a base64 value"),+ f"The `vertex_credentials` value is base64-encoded JSON, not the JSON itself. {VALUE_ADVICE}",+ encoded,+ )diff --git a/tests/unit/llms/vertex_ai/test_vertex_ai_non_gemini.py b/tests/unit/llms/vertex_ai/test_vertex_ai_non_gemini.pynew file mode 100644index 00000000000..d01d595e3b7--- /dev/null+++ b/tests/unit/llms/vertex_ai/test_vertex_ai_non_gemini.py@@ -0,0 +1,39 @@+import logging++import pytest++import litellm++FILE_FAILURE = "Unable to load the vertex credentials file. LiteLLM's log names the path and the reason."+++def _complete_on_the_legacy_route(vertex_credentials: str) -> None:+ litellm.completion(+ model="vertex_ai/chat-bison",+ messages=[{"role": "user", "content": "hi"}],+ vertex_credentials=vertex_credentials,+ vertex_project="p",+ vertex_location="us-central1",+ )+++def test_a_missing_key_file_is_reported_as_a_file_failure(tmp_path, caplog):+ missing = tmp_path / "vertexai.json"++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(litellm.APIConnectionError, match=FILE_FAILURE):+ _complete_on_the_legacy_route(str(missing))++ assert repr(str(missing)) in caplog.text+ assert "No such file or directory" in caplog.text+++def test_a_key_file_is_read_and_handed_to_google_auth(tmp_path, caplog):+ not_a_key = tmp_path / "settings.json"+ not_a_key.write_text('{"hello": "world"}')++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(litellm.APIConnectionError, match=FILE_FAILURE):+ _complete_on_the_legacy_route(str(not_a_key))++ assert f"the credentials file at {str(not_a_key)!r} holds credentials that cannot be used" in caplog.textdiff --git a/tests/unit/llms/vertex_ai/test_vertex_llm_base.py b/tests/unit/llms/vertex_ai/test_vertex_llm_base.pyindex b65e0e1d59c..17a92b31284 100644--- a/tests/unit/llms/vertex_ai/test_vertex_llm_base.py+++ b/tests/unit/llms/vertex_ai/test_vertex_llm_base.py@@ -1,6 +1,11 @@import asyncio+import base64import jsonimport logging+import os+import pathlib+import re+import tracebackfrom typing import Finalfrom unittest.mock import MagicMock, call, patch@@ -1442,6 +1447,18 @@ class TestVertexBase:"aws_region_name": "us-east-1",}+ def test_extract_aws_params_keeps_values_that_are_not_strings(self):+ json_with_null_region = {+ "type": "external_account",+ "aws_region_name": None,+ "aws_session_name": 123,+ }++ assert VertexAIAwsWifAuth.extract_aws_params(json_with_null_region) == {+ "aws_region_name": None,+ "aws_session_name": 123,+ }+def test_credentials_from_aws_with_explicit_auth(self):"""Test that explicit AWS auth creates credentials via supplier, not metadata."""json_obj = {@@ -2186,6 +2203,362 @@ class TestVertexBase:assert not mock_get_lock.called, "Fast path should not acquire lock"+_ENCODED_VERTEX_KEY: Final = base64.b64encode(+ json.dumps({"type": "service_account", "private_key_id": "kid-123", "private_key": "MIIEvQIBADA???>>>"}).encode()+).decode()+++class TestVertexCredentialsSource:+ """A `vertex_credentials` path that cannot be read must not be reported as malformed JSON.++ Regression for https://github.com/BerriAI/litellm/issues/40166: dispatching on+ os.path.exists() sent a missing or unreadable path down the inline-JSON branch,+ where the path string itself was parsed and every failure came back as a+ JSONDecodeError blaming the key material.+ """++ FILE_FAILURE: Final = "Unable to load the vertex credentials file"++ def test_missing_credentials_file_names_the_read_failure_in_the_log(self, tmp_path, caplog):+ missing = tmp_path / "vertexai.json"++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=str(missing), project_id="p")++ message = str(exc_info.value)+ assert "not valid JSON" not in message+ assert str(missing) not in message+ assert repr(str(missing)) in caplog.text+ assert "No such file or directory" in caplog.text++ def test_unreadable_credentials_file_names_the_read_failure_in_the_log(self, tmp_path, caplog):+ # Present but not openable as a file, the same shape as a path on a mount+ # that has stopped serving reads.+ unreadable = tmp_path / "vertexai.json"+ unreadable.mkdir()++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=str(unreadable), project_id="p")++ assert str(unreadable) not in str(exc_info.value)+ assert repr(str(unreadable)) in caplog.text+ assert "Is a directory" in caplog.text+ assert "not valid JSON" not in caplog.text++ def test_malformed_credentials_file_logs_the_private_key_hint(self, tmp_path, caplog):+ malformed = tmp_path / "vertexai.json"+ malformed.write_text('{"type": "service_account", "private_key": "-----BEGIN\nPRIVATE KEY-----"}')++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=str(malformed), project_id="p")++ assert str(malformed) not in str(exc_info.value)+ assert repr(str(malformed)) in caplog.text+ assert "is not valid JSON" in caplog.text+ assert "private_key" in caplog.text++ def test_every_file_failure_gives_the_caller_the_same_message(self, tmp_path):+ """Callers allowed to send `vertex_credentials` must not learn what is on the proxy's disk."""+ directory = tmp_path / "directory.json"+ directory.mkdir()+ malformed = tmp_path / "malformed.json"+ malformed.write_text("{not json")+ not_an_object = tmp_path / "list.json"+ not_an_object.write_text("[1, 2]")+ not_a_key = tmp_path / "settings.json"+ not_a_key.write_text('{"hello": "world"}')+ bad_private_key = tmp_path / "bad-key.json"+ bad_private_key.write_text(+ '{"type": "service_account", "private_key": "x", "client_email": "[email protected]", "token_uri": "https://t"}'+ )+ paths = (tmp_path / "missing.json", directory, malformed, not_an_object, not_a_key, bad_private_key)++ def message_for(path: pathlib.Path) -> str:+ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=str(path), project_id="p")+ return str(exc_info.value)++ assert {message_for(path) for path in paths} == {+ "Unable to load the vertex credentials file. LiteLLM's log names the path and the reason."+ }++ NOT_A_KEY: Final = '{"hello": "world"}'++ def _google_auth_rejection(self) -> str:+ with pytest.raises(google.auth.exceptions.GoogleAuthError) as exc_info:+ VertexBase()._credentials_from_service_account(json.loads(self.NOT_A_KEY), scopes=None)+ return str(exc_info.value)++ def test_google_auth_rejecting_a_credentials_file_is_named_only_in_the_log(self, tmp_path, caplog):+ not_a_key = tmp_path / "settings.json"+ not_a_key.write_text(self.NOT_A_KEY)++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=str(not_a_key), project_id="p")++ rejection = self._google_auth_rejection()+ assert rejection not in "".join(traceback.format_exception(exc_info.value))+ assert repr(str(not_a_key)) in caplog.text+ assert rejection in caplog.text++ def test_google_auth_rejecting_inline_credentials_still_tells_the_caller_why(self):+ rejection = self._google_auth_rejection()++ with pytest.raises(ValueError, match=re.escape(rejection)) as exc_info:+ VertexBase().load_auth(credentials=self.NOT_A_KEY, project_id="p")++ assert self.FILE_FAILURE not in str(exc_info.value)++ def test_litellm_rejecting_a_credentials_file_is_not_blamed_on_google_auth(self, tmp_path, caplog):+ wif_without_region = tmp_path / "wif.json"+ wif_without_region.write_text(+ json.dumps(+ {+ "type": "external_account",+ "credential_source": {"environment_id": "aws1"},+ "aws_role_name": "arn:aws:iam::123456789012:role/MyRole",+ }+ )+ )++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=str(wif_without_region), project_id="p")++ assert "holds credentials that cannot be used: aws_region_name is required" in caplog.text+ assert "Google auth" not in caplog.text++ def test_a_credentials_file_too_large_to_be_a_key_is_not_read_whole(self, tmp_path, caplog):+ oversized = tmp_path / "vertexai.json"+ oversized.write_text("{" + " " * (1 << 20) + "}")++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=str(oversized), project_id="p")++ assert "larger than any credentials file" in caplog.text++ def test_a_credentials_file_holding_json_that_is_not_an_object_says_so_in_the_log(self, tmp_path, caplog):+ double_encoded = tmp_path / "vertexai.json"+ double_encoded.write_text(json.dumps(json.dumps({"type": "service_account"})))++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=str(double_encoded), project_id="p")++ assert "is JSON but not a JSON object" in caplog.text+ assert "not valid JSON" not in caplog.text++ def test_a_path_with_a_newline_cannot_forge_a_log_line(self, tmp_path, caplog):+ forged = str(tmp_path / "vertexai.json") + "\nLiteLLM:ERROR: forged entry"++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=forged, project_id="p")++ assert "\nLiteLLM:ERROR: forged entry" not in caplog.text+ assert "\\nLiteLLM:ERROR: forged entry" in caplog.text++ def test_a_value_too_long_to_be_a_path_is_logged_by_length_only(self, caplog):+ not_a_path = "not a path, " * 25++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=not_a_path, project_id="p")++ assert "not a path, not a path" not in caplog.text+ assert f"{len(not_a_path)}-character value" in caplog.text++ def test_malformed_inline_credentials_do_not_echo_the_credential(self):+ inline = (+ '{"type": "service_account", "private_key": '+ '"-----BEGIN PRIVATE KEY-----\nMIIEvQIBADA\n-----END PRIVATE KEY-----"}'+ )++ with pytest.raises(+ ValueError, match="The inline `vertex_credentials` value is not valid JSON"+ ) as exc_info:+ VertexBase().load_auth(credentials=inline, project_id="p")++ message = str(exc_info.value)+ assert "MIIEvQIBADA" not in message+ assert "unescaped newlines in private_key" in message++ def test_a_credential_misconfigured_as_a_path_is_not_echoed(self):+ """A value that is neither a path nor JSON must not come back in the message."""+ pem = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADA\n-----END PRIVATE KEY-----"++ with pytest.raises(ValueError, match=self.FILE_FAILURE) as exc_info:+ VertexBase().load_auth(credentials=pem, project_id="p")++ message = str(exc_info.value)+ assert "MIIEvQIBADA" not in message+ assert "BEGIN PRIVATE KEY" not in message++ def test_readable_credentials_file_is_still_loaded(self, tmp_path):+ creds_file = tmp_path / "vertexai.json"+ creds_file.write_text(json.dumps({"type": "service_account", "project_id": "from-file"}))+ vertex_base = VertexBase()+ mock_creds = MagicMock()+ mock_creds.project_id = "from-file"++ with (+ patch.object(vertex_base, "_credentials_from_service_account", return_value=mock_creds) as from_sa,+ patch.object(vertex_base, "refresh_auth"),+ ):+ creds, project_id = vertex_base.load_auth(credentials=str(creds_file), project_id=None)++ assert creds is mock_creds+ assert project_id == "from-file"+ assert from_sa.call_args.args[0] == {"type": "service_account", "project_id": "from-file"}++ @pytest.mark.parametrize("leading", ["", "\n "])+ def test_inline_credentials_json_is_still_parsed(self, leading):+ vertex_base = VertexBase()+ mock_creds = MagicMock()+ mock_creds.project_id = "from-inline"++ with (+ patch.object(vertex_base, "_credentials_from_service_account", return_value=mock_creds) as from_sa,+ patch.object(vertex_base, "refresh_auth"),+ ):+ creds, project_id = vertex_base.load_auth(+ credentials=leading + json.dumps({"type": "service_account", "project_id": "from-inline"}),+ project_id=None,+ )++ assert creds is mock_creds+ assert project_id == "from-inline"+ assert from_sa.call_args.args[0] == {"type": "service_account", "project_id": "from-inline"}++ def test_a_credential_misconfigured_as_a_path_is_not_logged_either(self, caplog):+ """The path reaches the log, so a credential put in that field must be scrubbed first."""+ pem = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADA\n-----END PRIVATE KEY-----"++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=pem, project_id="p")++ assert "MIIEvQIBADA" not in caplog.text+ assert "REDACTED" in caplog.text++ def test_a_path_open_rejects_outright_is_reported_not_raised_raw(self, caplog):+ """open() rejects some paths with a bare ValueError before any filesystem call."""+ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials="creds" + chr(0) + ".json", project_id="p")++ assert "embedded null" in caplog.text++ def test_a_file_whose_name_starts_with_a_brace_is_still_read(self, tmp_path, monkeypatch):+ """Shape dispatch must not strand a real file that happens to be named like JSON.++ The value has to be relative for this to bite: an absolute path never starts with+ a brace, so only "{vertex}.json" reaches the inline branch and needs the fallback.+ """+ braced = tmp_path / "{vertex}.json"+ braced.write_text(json.dumps({"type": "service_account", "project_id": "from-braced-file"}))+ monkeypatch.chdir(tmp_path)+ vertex_base = VertexBase()+ mock_creds = MagicMock()+ mock_creds.project_id = "from-braced-file"++ with (+ patch.object(vertex_base, "_credentials_from_service_account", return_value=mock_creds) as from_sa,+ patch.object(vertex_base, "refresh_auth"),+ ):+ creds, project_id = vertex_base.load_auth(credentials="{vertex}.json", project_id=None)++ assert creds is mock_creds+ assert project_id == "from-braced-file"+ assert from_sa.call_args.args[0] == {"type": "service_account", "project_id": "from-braced-file"}++ @pytest.mark.parametrize(+ "encoded",+ [+ pytest.param(_ENCODED_VERTEX_KEY, id="padded"),+ pytest.param(_ENCODED_VERTEX_KEY.rstrip("="), id="unpadded"),+ pytest.param('"' + _ENCODED_VERTEX_KEY + '"', id="quoted"),+ pytest.param("base64:" + _ENCODED_VERTEX_KEY, id="prefixed"),+ pytest.param(_ENCODED_VERTEX_KEY.replace("+", "-").replace("/", "_"), id="urlsafe"),+ pytest.param("\n".join(_ENCODED_VERTEX_KEY[i : i + 64] for i in range(0, len(_ENCODED_VERTEX_KEY), 64)), id="wrapped"),+ ],+ )+ def test_base64_encoded_credentials_are_named_and_kept_out_of_the_log(self, encoded, caplog):+ with caplog.at_level(logging.DEBUG, logger="LiteLLM"):+ with pytest.raises(ValueError, match="is base64-encoded JSON") as exc_info:+ VertexBase().load_auth(credentials=encoded, project_id="p")++ assert _ENCODED_VERTEX_KEY[8:40] not in str(exc_info.value)+ assert _ENCODED_VERTEX_KEY[8:40] not in caplog.text++ @pytest.mark.parametrize(+ ("wrapped", "expected"),+ [+ pytest.param(+ json.dumps(json.dumps({"type": "service_account"})),+ "The `vertex_credentials` value is JSON but not a JSON object, it may be quoted or encoded twice",+ id="double-encoded",+ ),+ pytest.param(+ "'" + json.dumps({"type": "service_account"}) + "'",+ "is not valid JSON: .* Remove the quotes or byte-order mark before the opening",+ id="single-quoted",+ ),+ pytest.param(+ "\ufeff" + json.dumps({"type": "service_account"}),+ "is not valid JSON: .* Remove the quotes or byte-order mark before the opening",+ id="byte-order-mark",+ ),+ ],+ )+ def test_wrapped_inline_json_is_reported_as_inline_not_as_a_file(self, wrapped, expected):+ with pytest.raises(ValueError, match=expected):+ VertexBase().load_auth(credentials=wrapped, project_id="p")++ @pytest.mark.parametrize("empty", ["", " \n"])+ def test_an_empty_value_is_named_as_empty(self, empty):+ with pytest.raises(ValueError, match="The `vertex_credentials` value is empty"):+ VertexBase().load_auth(credentials=empty, project_id="p")++ def test_a_malformed_file_named_like_json_is_reported_as_a_bad_file(self, tmp_path, monkeypatch, caplog):+ (tmp_path / "{vertex}.json").write_text('{"type": "service_account",')+ monkeypatch.chdir(tmp_path)++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials="{vertex}.json", project_id="p")++ assert "'{vertex}.json' is not valid JSON" in caplog.text++ @pytest.mark.skipif(os.geteuid() == 0, reason="root ignores file permissions")+ def test_an_unreadable_file_named_like_json_is_reported_as_a_bad_file(self, tmp_path, monkeypatch, caplog):+ braced = tmp_path / "{vertex}.json"+ braced.write_text(json.dumps({"type": "service_account"}))+ braced.chmod(0)+ monkeypatch.chdir(tmp_path)++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials="{vertex}.json", project_id="p")++ assert "cannot read the credentials file at '{vertex}.json': Permission denied" in caplog.text++ def test_a_credentials_file_that_is_not_text_is_reported_as_such(self, tmp_path, caplog):+ not_text = tmp_path / "vertexai.json"+ not_text.write_bytes(bytes([0xFF, 0xFE, 0x00, 0x01]))++ with caplog.at_level(logging.ERROR, logger="LiteLLM"):+ with pytest.raises(ValueError, match=self.FILE_FAILURE):+ VertexBase().load_auth(credentials=str(not_text), project_id="p")++ assert "is not UTF-8 text" in caplog.text++def test_get_access_token_reraises_malformed_service_account_credentials_without_caching(caplog):vertex_base: Final = VertexBase()diff --git a/tests/unit/test_secret_redaction.py b/tests/unit/test_secret_redaction.pyindex 1c1cfe56754..3b0e9390a61 100644--- a/tests/unit/test_secret_redaction.py+++ b/tests/unit/test_secret_redaction.py@@ -466,15 +466,30 @@ def test_service_account_blob_fully_redacted():def test_vertex_error_message_no_credential_leak():- """The old Vertex error format leaked the full credential JSON.- The new format must not contain any credential material."""- new_msg = (- "Unable to load vertex credentials from environment. "- "Ensure the JSON is valid (check for unescaped newlines in private_key). "- "Parse error: JSONDecodeError"+ """The old Vertex error format leaked the full credential JSON. Every message the+ credential loader raises today must survive redaction unchanged, which it only can+ if it never carried credential material in the first place."""+ from litellm.llms.vertex_ai.credentials_source import (+ VertexCredentialsFileInvalid,+ VertexCredentialsFileUnreadable,+ VertexCredentialsInlineNotJson,+ raise_vertex_credentials_failure,+ )+ path = "/etc/litellm/vertexai.json"+ failures = (+ VertexCredentialsFileUnreadable(path, "No such file or directory (FileNotFoundError)"),+ VertexCredentialsFileInvalid(path, "Invalid control character at: line 1 column 55"),+ VertexCredentialsInlineNotJson(+ "Expecting value: line 1 column 1 (char 0)", "Check for unescaped newlines in private_key."+ ),)- result = redact_string(new_msg)- assert result == new_msg # nothing to redact++ for failure in failures:+ with pytest.raises(ValueError, match="vertex") as exc_info:+ raise_vertex_credentials_failure(failure)+ message = str(exc_info.value)+ assert path not in message # the path goes to the log, not to the API caller+ assert redact_string(message) == message # nothing to redactdef test_vertex_traceback_redacts_pem():