use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use azure_core::credentials::{Secret, TokenCredential};
use azure_identity::{ClientSecretCredential, DeveloperToolsCredential, ManagedIdentityCredential};
use eyre::Result;
use rig_core::providers::anthropic;
use tokio::sync::Mutex;
use crate::config::ProviderType;
use crate::llm::{
Completion, CompletionResponse, LLMClient, LLMClientDyn, RigClient, provider_error_has_code,
provider_http_status,
};
pub const DEFAULT_SCOPE: &str = "https://cognitiveservices.azure.com/.default";
const EXPIRY_SKEW_SECS: i64 = 60;
type RebuildFn = Box<dyn Fn(&str) -> Result<Arc<dyn LLMClientDyn>> + Send + Sync>;
struct Cached {
client: Arc<dyn LLMClientDyn>,
expires_at_unix: i64,
}
pub struct AzureAdClient {
credentials: Vec<Arc<dyn TokenCredential>>,
scope: String,
rebuild: RebuildFn,
cache: Mutex<Option<Cached>>,
}
impl AzureAdClient {
async fn fetch_token(&self) -> Result<(String, i64)> {
let scopes = [self.scope.as_str()];
let mut errors = Vec::new();
for cred in &self.credentials {
match cred.get_token(&scopes, None).await {
Ok(token) => {
return Ok((
token.token.secret().to_string(),
token.expires_on.unix_timestamp(),
));
}
Err(err) => errors.push(format_error_chain(&err)),
}
}
eyre::bail!(
"no Azure credential could obtain a token for scope {}: {}",
self.scope,
errors.join("; ")
);
}
async fn ensure_client(&self) -> Result<Arc<dyn LLMClientDyn>> {
let mut guard = self.cache.lock().await;
if let Some(cached) = guard.as_ref()
&& cached.expires_at_unix - now_unix() > EXPIRY_SKEW_SECS
{
return Ok(Arc::clone(&cached.client));
}
let (client, cached) = self.build_fresh().await?;
*guard = Some(cached);
Ok(client)
}
async fn refresh(&self, stale: &Arc<dyn LLMClientDyn>) -> Result<Arc<dyn LLMClientDyn>> {
let mut guard = self.cache.lock().await;
if let Some(cached) = guard.as_ref()
&& !Arc::ptr_eq(&cached.client, stale)
{
return Ok(Arc::clone(&cached.client));
}
let (client, cached) = self.build_fresh().await?;
*guard = Some(cached);
Ok(client)
}
async fn build_fresh(&self) -> Result<(Arc<dyn LLMClientDyn>, Cached)> {
let (token, expires_at_unix) = self.fetch_token().await?;
let client = (self.rebuild)(&token)?;
let cached = Cached {
client: Arc::clone(&client),
expires_at_unix,
};
Ok((client, cached))
}
}
impl LLMClient for AzureAdClient {
async fn completion(&self, completion: Completion) -> Result<CompletionResponse> {
let client = self.ensure_client().await?;
match client.completion(completion.clone()).await {
Ok(response) => Ok(response),
Err(err) if is_unauthorized(&err) => {
let client = self.refresh(&client).await?;
client.completion(completion).await
}
Err(err) => Err(err),
}
}
}
pub fn build_azure_client(
provider: &ProviderType,
base_url: Option<&str>,
scope: Option<&str>,
credentials: Option<&str>,
) -> Result<AzureAdClient> {
let base_url = resolve_base_url(base_url)?;
let scope = resolve_scope(scope);
let credentials = build_credential_chain(credentials)?;
let rebuild: RebuildFn = match provider {
ProviderType::OpenAi => {
let base = base_url.clone();
Box::new(move |token: &str| {
Ok(RigClient::openai(token, Some(&base)).into_arc())
})
}
ProviderType::Anthropic => {
let base = base_url.clone();
Box::new(move |token: &str| {
let mut config = anthropic::AnthropicConfig::new(token).with_base_url(&base);
config.dialect.quirks.auth = anthropic::wire::Auth::OptionalBearer;
Ok(RigClient::Anthropic(config, true).into_arc())
})
}
_ => eyre::bail!(
"auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
),
};
Ok(AzureAdClient {
credentials,
scope,
rebuild,
cache: Mutex::new(None),
})
}
fn resolve_base_url(base_url: Option<&str>) -> Result<String> {
base_url
.map(str::trim)
.filter(|u| !u.is_empty())
.map(str::to_string)
.ok_or_else(|| {
eyre::eyre!("auth = \"azure-ad\" requires `base_url` (the Azure Foundry endpoint)")
})
}
fn resolve_scope(scope: Option<&str>) -> String {
scope
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or(DEFAULT_SCOPE)
.to_string()
}
fn format_error_chain(err: &dyn std::error::Error) -> String {
let mut out = err.to_string();
let mut source = err.source();
while let Some(cause) = source {
out.push_str(": ");
out.push_str(&cause.to_string());
source = cause.source();
}
out
}
fn build_credential_chain(mode: Option<&str>) -> Result<Vec<Arc<dyn TokenCredential>>> {
let mode = mode
.map(str::to_string)
.or_else(|| std::env::var("AZURE_TOKEN_CREDENTIALS").ok())
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "auto".to_string());
let mut chain: Vec<Arc<dyn TokenCredential>> = Vec::new();
match mode.as_str() {
"dev" => {
if let Ok(dev) = DeveloperToolsCredential::new(None) {
chain.push(dev);
}
}
"prod" => {
push_env_service_principal(&mut chain);
if let Ok(mi) = ManagedIdentityCredential::new(None) {
chain.push(mi);
}
}
"auto" => {
push_env_service_principal(&mut chain);
if let Ok(mi) = ManagedIdentityCredential::new(None) {
chain.push(mi);
}
if let Ok(dev) = DeveloperToolsCredential::new(None) {
chain.push(dev);
}
}
other => {
eyre::bail!(
"unknown azure_credentials value \"{other}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
);
}
}
if chain.is_empty() {
eyre::bail!("no Azure credentials could be constructed for mode \"{mode}\"");
}
Ok(chain)
}
fn push_env_service_principal(chain: &mut Vec<Arc<dyn TokenCredential>>) {
let (Ok(tenant), Ok(client_id), Ok(secret)) = (
std::env::var("AZURE_TENANT_ID"),
std::env::var("AZURE_CLIENT_ID"),
std::env::var("AZURE_CLIENT_SECRET"),
) else {
return;
};
if let Ok(cred) = ClientSecretCredential::new(&tenant, client_id, Secret::new(secret), None) {
chain.push(cred);
}
}
fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
fn is_unauthorized(err: &eyre::Report) -> bool {
provider_http_status(err) == Some(401)
|| provider_error_has_code(err, &["authentication_error", "invalid_api_key"])
}
#[cfg(test)]
mod tests {
use super::*;
use rig_core::ProviderError as CompletionError;
fn provider_error(status: Option<u16>, body: &str) -> eyre::Report {
let error = match status {
Some(status) => CompletionError::from_http_response(
reqwest::StatusCode::from_u16(status).unwrap(),
body,
),
None => CompletionError::from_provider_body(body),
};
eyre::Report::new(error).wrap_err("Anthropic completion failed for model 'claude'")
}
#[test]
fn is_unauthorized_walks_the_chain() {
let err = provider_error(Some(401), r#"{"message":"Unauthorized"}"#);
let top_level = err.to_string().to_ascii_lowercase();
assert!(!top_level.contains("unauthorized"));
assert!(is_unauthorized(&err));
}
#[test]
fn is_unauthorized_false_for_unrelated_error() {
let err = provider_error(Some(500), r#"{"message":"boom"}"#);
assert!(!is_unauthorized(&err));
}
#[test]
fn is_unauthorized_false_for_403_with_unauthorized_text() {
let err = provider_error(
Some(403),
r#"{"message":"Unauthorized to use this deployment"}"#,
);
assert!(!is_unauthorized(&err));
}
#[test]
fn is_unauthorized_detects_provider_auth_types_without_status() {
let openai = provider_error(None, r#"{"error":{"code":"invalid_api_key"}}"#);
assert!(is_unauthorized(&openai));
let anthropic = provider_error(
None,
r#"{"type":"error","error":{"type":"authentication_error"}}"#,
);
assert!(is_unauthorized(&anthropic));
let permission = provider_error(None, r#"{"error":{"type":"permission_error"}}"#);
assert!(!is_unauthorized(&permission));
}
#[test]
fn resolve_scope_falls_back_on_empty_or_whitespace() {
assert_eq!(resolve_scope(None), DEFAULT_SCOPE);
assert_eq!(resolve_scope(Some("")), DEFAULT_SCOPE);
assert_eq!(resolve_scope(Some(" ")), DEFAULT_SCOPE);
let custom = "https://example.com/.default";
assert_eq!(resolve_scope(Some(custom)), custom);
assert_eq!(
resolve_scope(Some(" https://example.com/.default ")),
custom
);
}
#[test]
fn resolve_base_url_trims_and_rejects_empty() {
let url = "https://res.services.ai.azure.com/openai/v1";
assert_eq!(resolve_base_url(Some(url)).unwrap(), url);
assert_eq!(
resolve_base_url(Some(" https://res.services.ai.azure.com/openai/v1 ")).unwrap(),
url
);
assert!(resolve_base_url(None).is_err());
assert!(resolve_base_url(Some("")).is_err());
assert!(resolve_base_url(Some(" ")).is_err());
}
#[test]
fn format_error_chain_joins_sources() {
#[derive(Debug)]
struct Inner;
impl std::fmt::Display for Inner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("az login required")
}
}
impl std::error::Error for Inner {}
#[derive(Debug)]
struct Outer(Inner);
impl std::fmt::Display for Outer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("credential failed")
}
}
impl std::error::Error for Outer {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
assert_eq!(
format_error_chain(&Outer(Inner)),
"credential failed: az login required"
);
assert_eq!(format_error_chain(&Inner), "az login required");
}
struct DummyClient;
impl LLMClient for DummyClient {
async fn completion(&self, _completion: Completion) -> Result<CompletionResponse> {
eyre::bail!("dummy client should not be called")
}
}
#[tokio::test]
async fn refresh_reuses_cache_when_another_call_already_refreshed() {
let cached_client: Arc<dyn LLMClientDyn> = DummyClient.into_arc();
let stale_client: Arc<dyn LLMClientDyn> = DummyClient.into_arc();
let rebuild: RebuildFn =
Box::new(|_: &str| panic!("rebuild must not run when another refresh already won"));
let client = AzureAdClient {
credentials: Vec::new(),
scope: DEFAULT_SCOPE.to_string(),
rebuild,
cache: Mutex::new(Some(Cached {
client: Arc::clone(&cached_client),
expires_at_unix: now_unix() + 3600,
})),
};
let returned = client.refresh(&stale_client).await.unwrap();
assert!(Arc::ptr_eq(&returned, &cached_client));
}
}