//! Credential resolution without context exposure. //! //! Credentials come from environment variables or explicit values, resolve //! without any network access, and can be checked for readiness //! independently of a model request. Registered holders are redacted in //! diagnostics, and updating one provider's credential can never disturb //! another. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; /// Where a credential comes from. #[derive(Clone, Debug, PartialEq, Eq)] pub enum CredentialSource { /// Read from this environment variable at resolve time. Env(String), /// An explicit value, typically from configuration or a plugin. Explicit(String), } /// A resolved credential with optional renewal. /// /// Carries a renewal closure, so it deliberately implements neither /// [`std::fmt::Debug`] nor equality; use [`Credential::describe`] for /// diagnostics. #[derive(Clone)] pub struct Credential { source: CredentialSource, expires_at: Option, renewed: Option Option + Send + Sync>>, } impl Credential { /// A credential read from an environment variable when needed. #[must_use] pub fn from_env(var: impl Into) -> Self { Self { source: CredentialSource::Env(var.into()), expires_at: None, renewed: None, } } /// A credential with an explicit value. #[must_use] pub fn explicit(value: impl Into) -> Self { Self { source: CredentialSource::Explicit(value.into()), expires_at: None, renewed: None, } } /// Attach an expiry; expired values must renew before use. #[must_use] pub fn expires_in(mut self, after: Duration) -> Self { self.expires_at = SystemTime::now().checked_add(after); self } /// Attach a renewal closure that returns a fresh value. #[must_use] pub fn renew_with(mut self, renew: Arc Option + Send + Sync>) -> Self { self.renewed = Some(renew); self } fn is_expired(&self) -> bool { self.expires_at.is_some_and(|at| SystemTime::now() >= at) } /// The secret value, resolving lazily and renewing when expired. /// /// # Errors /// /// Returns a [`smith::error::ProviderFault::Authentication`] fault when /// the source is empty, the value expired, or renewal failed. pub fn secret(&self) -> smith::error::Result { if self.is_expired() { if let Some(renew) = &self.renewed && let Some(fresh) = renew() { return Ok(fresh); } return Err(auth("credential expired and renewal failed")); } match &self.source { CredentialSource::Env(var) => std::env::var(var) .ok() .filter(|value| !value.is_empty()) .ok_or_else(|| auth(format!("environment variable {var} is empty or unset"))), CredentialSource::Explicit(value) => Ok(value.clone()), } } /// Whether a request could be dispatched with this credential now, /// checked without any network access. #[must_use] pub fn is_ready(&self) -> bool { !self.is_expired() && match &self.source { CredentialSource::Env(var) => { std::env::var(var).is_ok_and(|value| !value.is_empty()) } CredentialSource::Explicit(_) => true, } } } /// Redacted description; the secret value never appears. impl Credential { /// A redacted description safe for logs and diagnostics. #[must_use] pub fn describe(&self) -> String { match &self.source { CredentialSource::Env(var) => format!("env:{var}"), CredentialSource::Explicit(_) => "explicit:".to_string(), } } } /// Per-provider credential registry with concurrent update safety. #[derive(Clone, Default)] pub struct AuthRegistry { credentials: Arc>>, } impl AuthRegistry { /// An empty registry. #[must_use] pub fn new() -> Self { Self::default() } /// Register or replace the credential for one provider. pub fn set(&self, provider: impl Into, credential: Credential) { if let Ok(mut guard) = self.credentials.lock() { guard.insert(provider.into(), credential); } } /// The registered credential, when present. #[must_use] pub fn get(&self, provider: &str) -> Option { self.credentials .lock() .ok() .and_then(|guard| guard.get(provider).cloned()) } /// Whether the provider has a ready credential, without network access. #[must_use] pub fn is_ready(&self, provider: &str) -> bool { self.get(provider) .is_some_and(|credential| credential.is_ready()) } } fn auth(message: impl Into) -> smith::error::SmithError { smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: message.into(), }, } } #[cfg(test)] mod tests { use super::*; #[test] fn explicit_credential_resolves_and_redacts() { let credential = Credential::explicit("sk-test"); assert!(credential.is_ready()); assert_eq!(credential.secret().unwrap_or_default(), "sk-test"); assert_eq!(credential.describe(), "explicit:"); } #[test] fn expired_credential_renews_or_fails_explicitly() { let credential = Credential::explicit("old") .expires_in(Duration::from_millis(0)) .renew_with(Arc::new(|| Some("fresh".to_string()))); assert_eq!(credential.secret().unwrap_or_default(), "fresh"); let dead = Credential::explicit("old").expires_in(Duration::from_millis(0)); assert_eq!( dead.secret().err().map(|e| e.code().to_string()), Some("PROVIDER_AUTH".to_string()) ); assert!(!dead.is_ready()); } #[test] fn concurrent_updates_preserve_unrelated_providers() { let registry = AuthRegistry::new(); registry.set("anthropic", Credential::explicit("a")); registry.set("openai", Credential::explicit("o")); let writer = std::thread::spawn({ let registry = registry.clone(); move || { for round in 0..100 { registry.set("anthropic", Credential::explicit(format!("a{round}"))); } } }); for _ in 0..100 { assert!(registry.is_ready("openai")); assert!(registry.is_ready("anthropic")); } writer.join().ok(); } }