#[cfg(feature = "http")]
mod broker;
mod cached;
mod sources;
#[cfg(feature = "http")]
pub use broker::{BrokerAuth, TokenBroker, TokenBrokerConfig};
pub use cached::{CachedCredentials, DEFAULT_REFRESH_SKEW_MS};
pub use sources::{EnvCredentials, FnCredentials};
use std::fmt;
use futures::future::BoxFuture;
use crate::error::LlmError;
#[derive(Clone, PartialEq, Eq)]
pub struct Credential {
pub secret: String,
pub expires_at_ms: Option<u64>,
pub headers: Vec<(String, String)>,
pub base_url: Option<String>,
}
impl Credential {
pub fn new(secret: impl Into<String>) -> Self {
Self { secret: secret.into(), expires_at_ms: None, headers: Vec::new(), base_url: None }
}
pub fn expires_at(mut self, unix_ms: u64) -> Self {
self.expires_at_ms = Some(unix_ms);
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn is_expired_at(&self, now_ms: u64, skew_ms: u64) -> bool {
self.expires_at_ms.is_some_and(|exp| now_ms.saturating_add(skew_ms) >= exp)
}
}
pub fn unix_now_ms() -> u64 {
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
{
0
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
{
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
.unwrap_or(0)
}
}
impl fmt::Debug for Credential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Credential")
.field("secret", &"<redacted>")
.field("expires_at_ms", &self.expires_at_ms)
.field("headers", &self.headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
.field("base_url", &self.base_url)
.finish()
}
}
pub fn is_secure_endpoint(url: &str) -> bool {
if url.starts_with("https://") {
return true;
}
let Some(rest) = url.strip_prefix("http://") else {
return false;
};
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
let host = match authority.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or_default(),
None => authority.rsplit_once(':').map_or(authority, |(h, _)| h),
};
matches!(host, "localhost" | "::1" | "10.0.2.2")
|| host.parse::<std::net::Ipv4Addr>().is_ok_and(|ip| ip.is_loopback())
}
pub fn require_secure_endpoint(url: &str, what: &str) -> Result<(), LlmError> {
if is_secure_endpoint(url) {
Ok(())
} else {
Err(LlmError::Config(format!(
"{what} must use https:// (plain http is only allowed for localhost / 127.0.0.1 / 10.0.2.2)"
)))
}
}
pub trait CredentialSource: Send + Sync + fmt::Debug {
fn credential<'a>(&'a self, provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>>;
fn invalidate(&self, provider: &str) {
let _ = provider;
}
fn generation(&self) -> u64 {
0
}
}
#[derive(Clone)]
pub struct StaticCredential(Credential);
impl StaticCredential {
pub fn new(secret: impl Into<String>) -> Self {
Self(Credential::new(secret))
}
pub fn from_credential(credential: Credential) -> Self {
Self(credential)
}
}
impl fmt::Debug for StaticCredential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("StaticCredential(<redacted>)")
}
}
impl CredentialSource for StaticCredential {
fn credential<'a>(&'a self, _provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
Box::pin(futures::future::ready(Ok(self.0.clone())))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_never_shows_secrets() {
let c = Credential::new("sk-secret").header("x-tenant", "t-secret");
let text = format!("{c:?} {:?}", StaticCredential::new("sk-secret"));
assert!(!text.contains("sk-secret"));
assert!(!text.contains("t-secret"));
}
}