mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-04 01:48:57 +00:00
* refactor(rust): standardize Azure Messages module path * docs(rust): define shared types crate boundaries * refactor(rust): share request helpers and type Anthropic blocks * docs(rust): format shared type invariants as bullets * test(rust): parameterize repeated cases with rstest * refactor(rust): move Responses transform result into llms * fix(anthropic): validate chat and batch responses * docs(rust): clarify API format ownership boundaries * docs: clarify Rust error message construction * refactor(auth): keep shared Rust errors provider-neutral * refactor(rust): separate format contracts from provider policy * fix(rust): type Anthropic chat response text collection * fix(rust): pass audio secret sources through hosts * fix(rust): unblock batch lint and OCR error assertions * test(rust): assert response failures at the adapter boundary * refactor(rust): declare error messages with typed context * wip * fix(rust): adapt Bedrock error details * style(rust): cargo fmt bedrock audio transcription Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): adapt tests and dead code to typed error details Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): keep converse error contracts and read env secrets without litellm Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci(rust): raise the native wheel size gate to 45 MB Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(rust): tolerate missing usage in converse responses on the transcription route Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Yujong Lee <yujong@berri.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
708 lines
24 KiB
Rust
708 lines
24 KiB
Rust
use std::{collections::BTreeMap, future::Future, path::Path, pin::Pin, sync::Arc};
|
|
|
|
use gcp_auth::{CustomServiceAccount, TokenProvider};
|
|
use litellm_auth_types::{
|
|
CredentialPlacement, Error, InputSource, SecretValue, Sourced, http::apply_credential,
|
|
};
|
|
use moka::future::Cache;
|
|
use serde_json::{Map, Value};
|
|
use sha2::{Digest, Sha256};
|
|
|
|
#[cfg(feature = "google-sdk")]
|
|
mod sdk;
|
|
#[cfg(feature = "google-sdk")]
|
|
pub use sdk::GoogleCredentials;
|
|
|
|
const CLOUD_PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform";
|
|
const GOOGLE_OAUTH_TOKEN_ENDPOINT: &str = "https://oauth2.googleapis.com/token";
|
|
const GOOGLE_APPLICATION_CREDENTIALS_ENV: &str = "GOOGLE_APPLICATION_CREDENTIALS";
|
|
const VERTEX_AI_API_KEY_ENV: &str = "VERTEX_AI_API_KEY";
|
|
const VERTEXAI_API_KEY_ENV: &str = "VERTEXAI_API_KEY";
|
|
const VERTEXAI_CREDENTIALS_ENV: &str = "VERTEXAI_CREDENTIALS";
|
|
const VERTEXAI_PROJECT_ENV: &str = "VERTEXAI_PROJECT";
|
|
const VERTEXAI_LOCATION_ENV: &str = "VERTEXAI_LOCATION";
|
|
const VERTEX_LOCATION_ENV: &str = "VERTEX_LOCATION";
|
|
|
|
pub const SECRET_NAMES: &[&str] = &[
|
|
VERTEX_AI_API_KEY_ENV,
|
|
VERTEXAI_API_KEY_ENV,
|
|
VERTEXAI_CREDENTIALS_ENV,
|
|
GOOGLE_APPLICATION_CREDENTIALS_ENV,
|
|
VERTEXAI_PROJECT_ENV,
|
|
VERTEXAI_LOCATION_ENV,
|
|
VERTEX_LOCATION_ENV,
|
|
];
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
pub struct VertexConfig {
|
|
credentials: Option<Sourced<SecretValue>>,
|
|
project_id: Option<String>,
|
|
location: Option<String>,
|
|
}
|
|
|
|
impl VertexConfig {
|
|
pub fn new(
|
|
credentials: Option<Sourced<SecretValue>>,
|
|
project_id: Option<String>,
|
|
location: Option<String>,
|
|
) -> Self {
|
|
Self {
|
|
credentials: credentials.filter(|value| !value.value().expose().trim().is_empty()),
|
|
project_id: project_id.filter(|value| !value.trim().is_empty()),
|
|
location: location.filter(|value| !value.trim().is_empty()),
|
|
}
|
|
}
|
|
|
|
pub fn from_sourced_optional_params(
|
|
params: &Map<String, Value>,
|
|
sources: &BTreeMap<String, InputSource>,
|
|
) -> Result<Self, Error> {
|
|
Ok(Self::new(
|
|
optional_credentials(
|
|
params,
|
|
sources,
|
|
&["vertex_credentials", "vertex_ai_credentials"],
|
|
)?,
|
|
optional_string(params, &["vertex_project", "vertex_ai_project"])?,
|
|
optional_string(params, &["vertex_location", "vertex_ai_location"])?,
|
|
))
|
|
}
|
|
|
|
pub fn or_configured(self, project_id: Option<&str>, location: Option<&str>) -> Self {
|
|
let configured =
|
|
|value: Option<&str>| value.filter(|value| !value.is_empty()).map(str::to_string);
|
|
Self {
|
|
project_id: self.project_id.or_else(|| configured(project_id)),
|
|
location: self.location.or_else(|| configured(location)),
|
|
..self
|
|
}
|
|
}
|
|
|
|
pub fn project_id(&self) -> Option<&str> {
|
|
self.project_id.as_deref()
|
|
}
|
|
|
|
pub fn location(&self) -> Option<&str> {
|
|
self.location.as_deref()
|
|
}
|
|
}
|
|
|
|
pub struct VertexEnvironment {
|
|
pub headers: Vec<(String, String)>,
|
|
pub project_id: String,
|
|
}
|
|
|
|
struct VertexAccessToken {
|
|
token: String,
|
|
project_id: String,
|
|
}
|
|
|
|
pub fn get_vertex_ai_project(
|
|
config: &VertexConfig,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> Option<String> {
|
|
config
|
|
.project_id()
|
|
.map(str::to_string)
|
|
.or_else(|| non_empty_env(env_lookup, VERTEXAI_PROJECT_ENV))
|
|
}
|
|
|
|
pub fn get_vertex_ai_location(
|
|
config: &VertexConfig,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> Option<String> {
|
|
config
|
|
.location()
|
|
.map(str::to_string)
|
|
.or_else(|| non_empty_env(env_lookup, VERTEXAI_LOCATION_ENV))
|
|
.or_else(|| non_empty_env(env_lookup, VERTEX_LOCATION_ENV))
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct VertexAuth {
|
|
providers: Cache<CredentialCacheKey, Arc<dyn VertexTokenSource>>,
|
|
loader: Arc<dyn VertexProviderLoader>,
|
|
}
|
|
|
|
impl Default for VertexAuth {
|
|
fn default() -> Self {
|
|
Self::new(Arc::new(GcpProviderLoader))
|
|
}
|
|
}
|
|
|
|
impl VertexAuth {
|
|
pub fn new(loader: Arc<dyn VertexProviderLoader>) -> Self {
|
|
Self {
|
|
providers: Cache::builder().max_capacity(64).build(),
|
|
loader,
|
|
}
|
|
}
|
|
|
|
pub async fn access_token(
|
|
&self,
|
|
config: &VertexConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<String, Error> {
|
|
self.load_provider(config, env_lookup).await?.token().await
|
|
}
|
|
|
|
pub async fn validate_environment(
|
|
&self,
|
|
headers: Vec<(String, String)>,
|
|
api_key: Option<&str>,
|
|
config: &VertexConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<VertexEnvironment, Error> {
|
|
let has_authorization = headers
|
|
.iter()
|
|
.any(|(name, _)| name.eq_ignore_ascii_case("Authorization"));
|
|
let static_token = api_key
|
|
.map(str::trim)
|
|
.filter(|value| !value.is_empty())
|
|
.map(str::to_string)
|
|
.or_else(|| non_empty_env(env_lookup, VERTEX_AI_API_KEY_ENV))
|
|
.or_else(|| non_empty_env(env_lookup, VERTEXAI_API_KEY_ENV));
|
|
let project_id = get_vertex_ai_project(config, env_lookup);
|
|
|
|
if !has_authorization && static_token.is_none() {
|
|
let access = self.get_access_token(config, env_lookup).await?;
|
|
return Ok(VertexEnvironment {
|
|
headers: apply_credential(headers, &access.token, CredentialPlacement::Bearer)?,
|
|
project_id: project_id.unwrap_or(access.project_id),
|
|
});
|
|
}
|
|
|
|
let project_id = match project_id {
|
|
Some(project_id) => project_id,
|
|
None => {
|
|
self.load_provider(config, env_lookup)
|
|
.await?
|
|
.project_id()
|
|
.await?
|
|
}
|
|
};
|
|
let headers = if has_authorization {
|
|
headers
|
|
} else {
|
|
apply_credential(
|
|
headers,
|
|
static_token.as_deref().expect("static token was checked"),
|
|
CredentialPlacement::Bearer,
|
|
)?
|
|
};
|
|
Ok(VertexEnvironment {
|
|
headers,
|
|
project_id,
|
|
})
|
|
}
|
|
|
|
async fn get_access_token(
|
|
&self,
|
|
config: &VertexConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<VertexAccessToken, Error> {
|
|
let provider = self.load_provider(config, env_lookup).await?;
|
|
let (token, project_id) = tokio::try_join!(provider.token(), provider.project_id())?;
|
|
Ok(VertexAccessToken { token, project_id })
|
|
}
|
|
|
|
async fn load_provider(
|
|
&self,
|
|
config: &VertexConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<Arc<dyn VertexTokenSource>, Error> {
|
|
let source = credential_source(config, env_lookup);
|
|
let key = source.cache_key();
|
|
self.providers
|
|
.try_get_with(key, self.loader.load(source))
|
|
.await
|
|
.map_err(|error| (*error).clone())
|
|
}
|
|
}
|
|
|
|
pub trait VertexTokenSource: Send + Sync {
|
|
fn project_id(&self) -> VertexAuthFuture<'_, String>;
|
|
fn token(&self) -> VertexAuthFuture<'_, String>;
|
|
}
|
|
|
|
pub trait VertexProviderLoader: Send + Sync {
|
|
fn load(&self, source: CredentialSource) -> VertexAuthFuture<'_, Arc<dyn VertexTokenSource>>;
|
|
}
|
|
|
|
pub type VertexAuthFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;
|
|
|
|
struct GcpTokenSource(Arc<dyn TokenProvider>);
|
|
|
|
impl VertexTokenSource for GcpTokenSource {
|
|
fn project_id(&self) -> VertexAuthFuture<'_, String> {
|
|
Box::pin(async move {
|
|
self.0
|
|
.project_id()
|
|
.await
|
|
.map(|project| project.to_string())
|
|
.map_err(auth_acquisition_error)
|
|
})
|
|
}
|
|
|
|
fn token(&self) -> VertexAuthFuture<'_, String> {
|
|
Box::pin(async move {
|
|
self.0
|
|
.token(&[CLOUD_PLATFORM_SCOPE])
|
|
.await
|
|
.map(|token| token.as_str().to_string())
|
|
.map_err(auth_acquisition_error)
|
|
})
|
|
}
|
|
}
|
|
|
|
struct GcpProviderLoader;
|
|
|
|
impl VertexProviderLoader for GcpProviderLoader {
|
|
fn load(&self, source: CredentialSource) -> VertexAuthFuture<'_, Arc<dyn VertexTokenSource>> {
|
|
Box::pin(async move {
|
|
let provider: Arc<dyn TokenProvider> = match source {
|
|
CredentialSource::Inline(configured) => Arc::new(
|
|
CustomServiceAccount::from_json(validate_request_credentials(
|
|
configured.expose(),
|
|
)?)
|
|
.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)
|
|
}
|
|
CredentialSource::ApplicationCredentials(path) => {
|
|
Arc::new(CustomServiceAccount::from_file(path).map_err(auth_acquisition_error)?)
|
|
}
|
|
CredentialSource::Adc => {
|
|
gcp_auth::provider().await.map_err(auth_acquisition_error)?
|
|
}
|
|
};
|
|
Ok(Arc::new(GcpTokenSource(provider)) as Arc<dyn VertexTokenSource>)
|
|
})
|
|
}
|
|
}
|
|
|
|
fn validate_request_credentials(configured: &str) -> Result<&str, Error> {
|
|
let token_uri = serde_json::from_str::<Value>(configured)
|
|
.ok()
|
|
.and_then(|credentials| {
|
|
credentials
|
|
.get("token_uri")
|
|
.and_then(Value::as_str)
|
|
.map(str::to_string)
|
|
});
|
|
if token_uri.as_deref() != Some(GOOGLE_OAUTH_TOKEN_ENDPOINT) {
|
|
return Err(Error::InvalidConfiguration("request-controlled Vertex credentials must use the canonical Google OAuth token endpoint".into()));
|
|
}
|
|
Ok(configured)
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub enum CredentialSource {
|
|
Inline(SecretValue),
|
|
Trusted(SecretValue),
|
|
ApplicationCredentials(String),
|
|
Adc,
|
|
}
|
|
|
|
impl CredentialSource {
|
|
fn cache_key(&self) -> CredentialCacheKey {
|
|
match self {
|
|
Self::Inline(configured) => {
|
|
CredentialCacheKey::Inline(Sha256::digest(configured.expose()).into())
|
|
}
|
|
Self::Trusted(configured) => {
|
|
CredentialCacheKey::Trusted(Sha256::digest(configured.expose()).into())
|
|
}
|
|
Self::ApplicationCredentials(path) => {
|
|
CredentialCacheKey::ApplicationCredentials(path.clone())
|
|
}
|
|
Self::Adc => CredentialCacheKey::Adc,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
|
|
enum CredentialCacheKey {
|
|
Inline([u8; 32]),
|
|
Trusted([u8; 32]),
|
|
ApplicationCredentials(String),
|
|
Adc,
|
|
}
|
|
|
|
fn credential_source(
|
|
config: &VertexConfig,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> CredentialSource {
|
|
if let Some(configured) = config.credentials.clone() {
|
|
return match configured.source() {
|
|
InputSource::Request => CredentialSource::Inline(configured.into_value()),
|
|
InputSource::Deployment | InputSource::Environment => {
|
|
CredentialSource::Trusted(configured.into_value())
|
|
}
|
|
};
|
|
}
|
|
if let Some(configured) = non_empty_env(env_lookup, VERTEXAI_CREDENTIALS_ENV) {
|
|
return CredentialSource::Trusted(SecretValue::new(configured));
|
|
}
|
|
non_empty_env(env_lookup, GOOGLE_APPLICATION_CREDENTIALS_ENV)
|
|
.map(CredentialSource::ApplicationCredentials)
|
|
.unwrap_or(CredentialSource::Adc)
|
|
}
|
|
|
|
fn optional_credentials(
|
|
params: &Map<String, Value>,
|
|
sources: &BTreeMap<String, InputSource>,
|
|
names: &[&str],
|
|
) -> Result<Option<Sourced<SecretValue>>, Error> {
|
|
for name in names {
|
|
let source = source_for(sources, name);
|
|
match params.get(*name) {
|
|
None | Some(Value::Null) => continue,
|
|
Some(Value::String(value)) if value.trim().is_empty() => continue,
|
|
Some(Value::String(value)) => {
|
|
return Ok(Some(Sourced::new(SecretValue::new(value), source)));
|
|
}
|
|
Some(Value::Object(value)) if value.is_empty() => continue,
|
|
Some(Value::Object(value)) => {
|
|
return serde_json::to_string(value)
|
|
.map(SecretValue::new)
|
|
.map(|value| Sourced::new(value, source))
|
|
.map(Some)
|
|
.map_err(|error| {
|
|
Error::InvalidConfiguration(litellm_auth_types::ErrorDetail::failed(
|
|
"credential serialization",
|
|
error,
|
|
))
|
|
});
|
|
}
|
|
Some(_) => {
|
|
return Err(Error::InvalidConfiguration(
|
|
litellm_auth_types::ErrorDetail::InvalidType {
|
|
field: names[0].into(),
|
|
expected: "a string or null",
|
|
},
|
|
));
|
|
}
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn source_for(sources: &BTreeMap<String, InputSource>, name: &str) -> InputSource {
|
|
sources.get(name).copied().unwrap_or_default()
|
|
}
|
|
|
|
fn optional_string(params: &Map<String, Value>, names: &[&str]) -> Result<Option<String>, Error> {
|
|
for name in names {
|
|
match params.get(*name) {
|
|
None | Some(Value::Null) => continue,
|
|
Some(Value::String(value)) if value.trim().is_empty() => continue,
|
|
Some(Value::String(value)) => return Ok(Some(value.clone())),
|
|
Some(_) => {
|
|
return Err(Error::InvalidConfiguration(
|
|
litellm_auth_types::ErrorDetail::InvalidType {
|
|
field: names[0].into(),
|
|
expected: "a string or null",
|
|
},
|
|
));
|
|
}
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn non_empty_env(env_lookup: &dyn Fn(&str) -> Option<String>, name: &str) -> Option<String> {
|
|
env_lookup(name)
|
|
.map(|value| value.trim().to_string())
|
|
.filter(|value| !value.is_empty())
|
|
}
|
|
|
|
fn auth_acquisition_error(error: gcp_auth::Error) -> Error {
|
|
Error::CredentialAcquisition(litellm_auth_types::ErrorDetail::failed(
|
|
"Vertex AI credentials",
|
|
error,
|
|
))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use std::collections::BTreeSet;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
use serde_json::json;
|
|
|
|
use super::*;
|
|
|
|
struct FakeProvider {
|
|
calls: Arc<AtomicUsize>,
|
|
}
|
|
|
|
impl VertexTokenSource for FakeProvider {
|
|
fn project_id(&self) -> VertexAuthFuture<'_, String> {
|
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
|
Box::pin(async { Ok("adc-project".into()) })
|
|
}
|
|
|
|
fn token(&self) -> VertexAuthFuture<'_, String> {
|
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
|
Box::pin(async { Ok("adc-token".into()) })
|
|
}
|
|
}
|
|
|
|
struct FakeLoader {
|
|
loads: Arc<AtomicUsize>,
|
|
provider: Arc<dyn VertexTokenSource>,
|
|
}
|
|
|
|
impl VertexProviderLoader for FakeLoader {
|
|
fn load(
|
|
&self,
|
|
_source: CredentialSource,
|
|
) -> VertexAuthFuture<'_, Arc<dyn VertexTokenSource>> {
|
|
let loads = self.loads.clone();
|
|
let provider = self.provider.clone();
|
|
Box::pin(async move {
|
|
loads.fetch_add(1, Ordering::SeqCst);
|
|
Ok(provider)
|
|
})
|
|
}
|
|
}
|
|
|
|
fn config(value: Value) -> VertexConfig {
|
|
VertexConfig::from_sourced_optional_params(value.as_object().unwrap(), &BTreeMap::new())
|
|
.unwrap()
|
|
}
|
|
|
|
fn auth(calls: Arc<AtomicUsize>, loads: Arc<AtomicUsize>) -> VertexAuth {
|
|
let provider: Arc<dyn VertexTokenSource> = Arc::new(FakeProvider { calls });
|
|
VertexAuth::new(Arc::new(FakeLoader { loads, provider }))
|
|
}
|
|
|
|
#[test]
|
|
fn config_is_typed_and_secrets_are_redacted() {
|
|
let config = config(json!({
|
|
"vertex_credentials":{"private_key":"secret-key"},
|
|
"vertex_project":"project-1",
|
|
"vertex_location":"europe-west4"
|
|
}));
|
|
assert_eq!(config.project_id(), Some("project-1"));
|
|
assert_eq!(config.location(), Some("europe-west4"));
|
|
assert!(!format!("{config:?}").contains("secret-key"));
|
|
assert!(
|
|
VertexConfig::from_sourced_optional_params(
|
|
json!({"vertex_credentials":true}).as_object().unwrap(),
|
|
&BTreeMap::new()
|
|
)
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn secret_names_cover_environment_reads() {
|
|
let seen = Arc::new(std::sync::Mutex::new(BTreeSet::<String>::new()));
|
|
let recorded = seen.clone();
|
|
let env = |name: &str| {
|
|
recorded.lock().unwrap().insert(name.to_string());
|
|
None
|
|
};
|
|
let auth = auth(Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
|
|
auth.validate_environment(Vec::new(), None, &VertexConfig::default(), &env)
|
|
.await
|
|
.unwrap();
|
|
get_vertex_ai_location(&VertexConfig::default(), &env);
|
|
assert!(
|
|
seen.lock()
|
|
.unwrap()
|
|
.iter()
|
|
.all(|name| SECRET_NAMES.contains(&name.as_str()))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn empty_primary_values_fall_back_to_python_aliases() {
|
|
let config = config(json!({
|
|
"vertex_credentials": null,
|
|
"vertex_ai_credentials": "alias-credentials",
|
|
"vertex_project": " ",
|
|
"vertex_ai_project": "alias-project",
|
|
"vertex_location": null,
|
|
"vertex_ai_location": "alias-location"
|
|
}));
|
|
assert_eq!(
|
|
config.credentials.as_ref().unwrap().value().expose(),
|
|
"alias-credentials"
|
|
);
|
|
assert_eq!(config.project_id(), Some("alias-project"));
|
|
assert_eq!(config.location(), Some("alias-location"));
|
|
}
|
|
|
|
#[test]
|
|
fn typed_config_preserves_source_and_empty_value_fallback() {
|
|
let configured = VertexConfig::new(
|
|
Some(Sourced::new(
|
|
SecretValue::new("inline-json"),
|
|
InputSource::Request,
|
|
)),
|
|
Some("project".into()),
|
|
Some("location".into()),
|
|
);
|
|
assert!(matches!(
|
|
credential_source(&configured, &|_| Some("environment-json".into())),
|
|
CredentialSource::Inline(value) if value.expose() == "inline-json"
|
|
));
|
|
let empty = VertexConfig::new(
|
|
Some(Sourced::new(SecretValue::new(" "), InputSource::Request)),
|
|
Some(" ".into()),
|
|
Some(" ".into()),
|
|
);
|
|
assert!(matches!(
|
|
credential_source(&empty, &|_| None),
|
|
CredentialSource::Adc
|
|
));
|
|
assert_eq!(
|
|
get_vertex_ai_project(&empty, &|_| Some("env-project".into())).as_deref(),
|
|
Some("env-project")
|
|
);
|
|
assert_eq!(
|
|
get_vertex_ai_location(&empty, &|_| Some("env-location".into())).as_deref(),
|
|
Some("env-location")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn project_and_location_prefer_input_then_environment() {
|
|
let configured =
|
|
config(json!({"vertex_project":"input-project","vertex_location":"input-location"}));
|
|
let env = |name: &str| Some(format!("env-{name}"));
|
|
assert_eq!(
|
|
get_vertex_ai_project(&configured, &env).as_deref(),
|
|
Some("input-project")
|
|
);
|
|
assert_eq!(
|
|
get_vertex_ai_location(&configured, &env).as_deref(),
|
|
Some("input-location")
|
|
);
|
|
let empty = VertexConfig::default();
|
|
assert_eq!(
|
|
get_vertex_ai_project(&empty, &|_| Some("env-project".into())).as_deref(),
|
|
Some("env-project")
|
|
);
|
|
assert_eq!(
|
|
get_vertex_ai_location(&empty, &|name| (name == VERTEX_LOCATION_ENV)
|
|
.then(|| "fallback-location".into()))
|
|
.as_deref(),
|
|
Some("fallback-location")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn credential_discovery_prefers_input_then_environment_then_adc() {
|
|
let params = json!({"vertex_credentials":"input-json"});
|
|
let sources = BTreeMap::from([("vertex_credentials".to_string(), InputSource::Request)]);
|
|
let configured =
|
|
VertexConfig::from_sourced_optional_params(params.as_object().unwrap(), &sources)
|
|
.unwrap();
|
|
assert!(
|
|
matches!(credential_source(&configured, &|_| Some("environment-value".into())), CredentialSource::Inline(value) if value.expose() == "input-json")
|
|
);
|
|
let empty = VertexConfig::default();
|
|
assert!(
|
|
matches!(credential_source(&empty, &|name| (name == VERTEXAI_CREDENTIALS_ENV).then(|| "environment-json".into())), CredentialSource::Trusted(value) if value.expose() == "environment-json")
|
|
);
|
|
assert!(
|
|
matches!(credential_source(&empty, &|name| (name == GOOGLE_APPLICATION_CREDENTIALS_ENV).then(|| "adc.json".into())), CredentialSource::ApplicationCredentials(path) if path == "adc.json")
|
|
);
|
|
assert!(matches!(
|
|
credential_source(&empty, &|_| None),
|
|
CredentialSource::Adc
|
|
));
|
|
assert_ne!(
|
|
CredentialSource::Inline(SecretValue::new("same-value")).cache_key(),
|
|
CredentialSource::Trusted(SecretValue::new("same-value")).cache_key()
|
|
);
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
#[case::canonical_endpoint(r#"{"token_uri":"https://oauth2.googleapis.com/token"}"#, true)]
|
|
#[case::noncanonical_endpoint(r#"{"token_uri":"http://127.0.0.1/token"}"#, false)]
|
|
#[case::missing_endpoint("{}", false)]
|
|
fn request_credentials_require_canonical_token_endpoint(
|
|
#[case] credentials: &str,
|
|
#[case] accepted: bool,
|
|
) {
|
|
assert_eq!(validate_request_credentials(credentials).is_ok(), accepted);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn explicit_token_and_header_do_not_acquire_adc() {
|
|
let loads = Arc::new(AtomicUsize::new(0));
|
|
let auth = auth(Arc::new(AtomicUsize::new(0)), loads.clone());
|
|
let configured = config(json!({"vertex_project":"project-1"}));
|
|
let explicit = auth
|
|
.validate_environment(Vec::new(), Some("access-token"), &configured, &|_| None)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(explicit.headers[0].1, "Bearer access-token");
|
|
let existing = auth
|
|
.validate_environment(
|
|
vec![("authorization".into(), "Bearer existing".into())],
|
|
None,
|
|
&configured,
|
|
&|_| None,
|
|
)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(existing.headers[0].1, "Bearer existing");
|
|
assert_eq!(loads.load(Ordering::SeqCst), 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn provider_is_reused_across_authentication_calls() {
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let loads = Arc::new(AtomicUsize::new(0));
|
|
let auth = auth(calls.clone(), loads.clone());
|
|
for _ in 0..2 {
|
|
let environment = auth
|
|
.validate_environment(Vec::new(), None, &VertexConfig::default(), &|_| None)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(environment.project_id, "adc-project");
|
|
assert_eq!(environment.headers[0].1, "Bearer adc-token");
|
|
}
|
|
assert_eq!(loads.load(Ordering::SeqCst), 1);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 4);
|
|
}
|
|
|
|
#[test]
|
|
fn configured_defaults_sit_between_call_params_and_the_environment() {
|
|
let env = |name: &str| Some(format!("env-{name}"));
|
|
let from_config =
|
|
VertexConfig::default().or_configured(Some("global-project"), Some("global-location"));
|
|
assert_eq!(
|
|
get_vertex_ai_project(&from_config, &env).as_deref(),
|
|
Some("global-project")
|
|
);
|
|
assert_eq!(
|
|
get_vertex_ai_location(&from_config, &env).as_deref(),
|
|
Some("global-location")
|
|
);
|
|
let from_call =
|
|
config(json!({"vertex_project":"call-project","vertex_location":"call-location"}))
|
|
.or_configured(Some("global-project"), Some("global-location"));
|
|
assert_eq!(from_call.project_id(), Some("call-project"));
|
|
assert_eq!(from_call.location(), Some("call-location"));
|
|
let empty_global = VertexConfig::default().or_configured(Some(""), None);
|
|
assert_eq!(
|
|
get_vertex_ai_project(&empty_global, &env).as_deref(),
|
|
Some("env-VERTEXAI_PROJECT")
|
|
);
|
|
}
|
|
}
|